可以用Python实现Xbox 360手柄的“震动”吗?

7

我能否使用Python实现无线Xbox 360 PC控制器的震动反馈?目前我只找到了读取输入信号的解决方案,但无法找到有关震动/反馈的信息。

编辑:

根据@AdamRosenfield提供的代码,我遇到了以下错误。

Traceback (most recent call last):
  File "C:\Users\Usuario\Desktop\rumble.py", line 8, in <module>
    xinput = ctypes.windll.Xinput  # Load Xinput.dll
  File "C:\Python27\lib\ctypes\__init__.py", line 435, in __getattr__
    dll = self._dlltype(name)
  File "C:\Python27\lib\ctypes\__init__.py", line 365, in __init__
    self._handle = _dlopen(self._name, mode)
WindowsError: [Error 126] The specified module could not be found. 

请注意,最后一个错误是从西班牙语翻译过来的。

1个回答

8

这是可能的,但并不容易。在C语言中,您可以使用XInputSetState()函数来控制震动。要从Python中访问它,您必须编译一个用C语言编写的Python扩展程序或使用ctypes

像这样的东西应该可以工作,但请记住我没有测试过:

import ctypes

# Define necessary structures
class XINPUT_VIBRATION(ctypes.Structure):
    _fields_ = [("wLeftMotorSpeed", ctypes.c_ushort),
                ("wRightMotorSpeed", ctypes.c_ushort)]

xinput = ctypes.windll.xinput1_1  # Load Xinput.dll

# Set up function argument types and return type
XInputSetState = xinput.XInputSetState
XInputSetState.argtypes = [ctypes.c_uint, ctypes.POINTER(XINPUT_VIBRATION)]
XInputSetState.restype = ctypes.c_uint

# Now we're ready to call it.  Set left motor to 100%, right motor to 50%
# for controller 0
vibration = XINPUT_VIBRATION(65535, 32768)
XInputSetState(0, ctypes.byref(vibration))

# You can also create a helper function like this:
def set_vibration(controller, left_motor, right_motor):
    vibration = XINPUT_VIBRATION(int(left_motor * 65535), int(right_motor * 65535))
    XInputSetState(controller, ctypes.byref(vibration))

# ... and use it like so
set_vibration(0, 1.0, 0.5)

谢谢回答,我在使用 "ctypes.struct" 时遇到错误:它不是一个有效的属性。而且我不知道 "ctypes.struct" 是从哪里来的! - Belohlavek
@Belohlavek:糟糕,应该是“Structure”,而不是“struct”。 - Adam Rosenfield
2
@Belohlavek:您是否已安装DirectX SDK?根据文档,XInput库仅默认安装在Windows Vista和Windows 8上。如果您已经安装了DirectX SDK但仍然找不到DLL,则需要使用类似于“xinput = ctypes.windll.LoadLibrary(r'C:\path\to\Xinput.dll')”这样的方法手动加载库。 - Adam Rosenfield
SDK的安装部分失败了。它安装了一些带有示例和代码的软件,但是它显示了一个错误消息告诉我安装失败了,我应该尝试关闭所有程序并重新运行它。但是没有用。我还尝试加载库,但DX SDK文件夹中没有DLL,我尝试使用System32上的DLL,但也不起作用(相同的ERROR 126消息)。震动示例(二进制文件)与我的控制器完全正常。此外,我有3个版本的Xinput_(数字)。dll! - Belohlavek
2
@Belohlavek:显然实际的DLL名称中包含版本号。尝试使用ctypes.windll.xinput1_1代替(或者xinput1_3XInput9_1_0,或者无论您的C:\Windows\System32\xinput<version>.dll的名称是什么)。 - Adam Rosenfield
显示剩余5条评论

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接