更新答案:
我在下面的评论中提到 PyAL 已经有一段时间没有更新了。事实上,虽然我链接的 bitbucket 存储库不再存在,但这并不准确。这PyAL 的 PyPI 页面 https://pypi.org/project/python-openal/最后日期为 12/25/2019,其中the repo https://github.com/NicklasTegner/PyAL截至本次更新之时,日期为 2020 年 9 月 11 日。相比之下,PyOpenAL 的 PyPI 页面 https://pypi.org/project/PyOpenAL/最后日期为 12/17/2019,其中the repo https://github.com/Zuzu-Typ/PyOpenAL日期也为 2019 年 12 月 17 日。我保留了下面的旧答案,并按照上面 @Caridorc 的要求添加了支持 PyOpenAL 的代码。
为了让 PyOpenAL 工作,我需要手动添加openal.dll
文件到已安装的库,以便可以通过以下方式找到依赖项其内部库加载实用程序 https://github.com/Zuzu-Typ/PyOpenAL/blob/master/openal/library_loader.py。我还需要避免为我的位置设置元组Listener
and Source
直接类并且必须使用set_position
而是调用方法,以便将位置更改传播到底层 C 库(ideally PyOpenAL
应修改为使用 @property 语法来无缝处理此问题).
两个演示中使用的波形声音文件是here https://www2.cs.uic.edu/%7Ei101/SoundFiles/CantinaBand60.wav。注意仅支持单声道,不支持立体声声音文件.
这是更新后的代码:
import time
from openal import *
if __name__ == "__main__":
x_pos = 5
sleep_time = 5
source = oalOpen("CantinaBand60.wav")
source.set_position([x_pos, 0, 0])
source.set_looping(True)
source.play()
listener = Listener()
listener.set_position([0, 0, 0])
while True:
source.set_position([x_pos, 0, 0])
print("Playing at: {0}".format(source.position))
time.sleep(sleep_time)
x_pos *= -1
oalQuit()
使用 PyAL 的旧答案:
事实证明,Bitbucket 存储库页面上有一些如何使用 PyAL 的示例here https://bitbucket.org/marcusva/py-al/src/bd5ae7f4b283177d6ec638000e3e246d8e572ca7/examples/?at=default。基于audioplayer.py
例如,我制作了这个听起来烦人的示例,根据正弦波在左右耳机扬声器之间进行声音替代:
import time
import math
from openal.audio import SoundSink, SoundSource
from openal.loaders import load_wav_file
if __name__ == "__main__":
sink = SoundSink()
sink.activate()
source = SoundSource(position=[0, 0, 0])
source.looping = True
data = load_wav_file("CantinaBand60.wav")
source.queue(data)
sink.play(source)
t = 0
while True:
x_pos = 5*math.sin(math.radians(t))
source.position = [x_pos, source.position[1], source.position[2]]
sink.update()
print("playing at %r" % source.position)
time.sleep(0.1)
t += 5