Pygame 播放背景音乐卡顿

hikali / 2024-02-17 / 原文

Pygame是常用的游戏开发库之一。然而在使用Pygame的过程中,却出现了播放背景音乐卡顿的问题。表现为咯咯咯的噪音。

检查Pygame版本,为2.5.2。降级至1.9.6,此时代码报错:

Traceback (most recent call last):
  File "D:\MyWork\Code_Learning\PythonLearning\Pygame\test2.py", line 4, in <module>
    pygame.mixer.init()
pygame.error: No available audio device

 没有可用音频设备。

改到2.0.0版本,代码又能正常运行,但卡顿再次出现。Python版本3.8.10。

看来这个问题大概是Pygame与底层音频驱动的交互问题。可能它找不到正常驱动,调用了兼容驱动,最终被套了多层接口,使得整体播放效率下降,音频出现卡顿。但我无法直接解决,这是Pygame自身的问题。

 

解决办法:

1. 改用winsound库来播放音乐。

坏处是必须使用wav格式的音频,占用较大。

好处是终于听见了正常的音乐声。

python内置库,所以不用安装。

 

2. 改用playsound库来播放音乐。

然而,这个第三方库有一些小bug。需要将原文件的第55行:

command = ' '.join(command).encode('utf-16')

更改为:

command = ' '.join(command)#.encode('utf-16')

不需要主动寻找文件。报错时会自动说文件的路径:

    Error 305 for command:
        open "C:\Users\16581\AppData\Local\Temp\PS_hj5h9ji.mp3"
    在用引号括起的字符串不能指定额外的字符。

    Error 263 for command:
        close "C:\Users\16581\AppData\Local\Temp\PS_hj5h9ji.mp3"
    指定的设备未打开,或不被 MCI 所识别。
Failed to close the file: "C:\Users\16581\AppData\Local\Temp\PS_hj5h9ji.mp3"
Traceback (most recent call last):
  File "D:\MyWork\Code_Learning\PythonLearning\Pygame\test2.py", line 8, in <module>
    playsound.playsound("./src/Hello_How are you.mp3")
  File "D:\MyWork\Code_Learning\PythonLearning\Pygame\Runtime3.8\lib\site-packages\playsound.py", line 44, in _playsoundWin
    _playsoundWin(tempPath, block)
  File "D:\MyWork\Code_Learning\PythonLearning\Pygame\Runtime3.8\lib\site-packages\playsound.py", line 72, in _playsoundWin
    winCommand(u'open {}'.format(sound))
  File "D:\MyWork\Code_Learning\PythonLearning\Pygame\Runtime3.8\lib\site-packages\playsound.py", line 64, in winCommand
    raise PlaysoundException(exceptionMessage)
playsound.PlaysoundException: 
    Error 305 for command:
        open "C:\Users\16581\AppData\Local\Temp\PS_hj5h9ji.mp3"
    在用引号括起的字符串不能指定额外的字符。

根据路径打开这个playsound.py文件(Pycharm就直接点路径点开)即可。

之所以报这个错,是因为python3默认的是utf-8的编码方式,而不是utf-16。这个第三方库有些画蛇添足。总之,去掉即可。

可以播放mp3文件。相较于第一个办法,减小了游戏发布大小。

 

此外playsound这个库还可能在安装时报错。当我从Python3.8.10迁移至3.11.8时,pip安装出现:

Collecting playsound
Using cached playsound-1.3.0.tar.gz (7.7 kB)
Installing build dependencies ... done
Getting requirements to build wheel ... error
error: subprocess-exited-with-error

× Getting requirements to build wheel did not run successfully.
│ exit code: 1
╰─> [29 lines of output]
Traceback (most recent call last):
File "/data/data/com.termux/files/usr/lib/python3.11/site-packages/pip/_vendor/pyproject_hooks/_in_process/_in_process.py", line 353, in
main()
File "/data/data/com.termux/files/usr/lib/python3.11/site-packages/pip/_vendor/pyproject_hooks/_in_process/_in_process.py", line 335, in main
json_out['return_val'] = hook(**hook_input['kwargs'])
^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "/data/data/com.termux/files/usr/lib/python3.11/site-packages/pip/_vendor/pyproject_hooks/_in_process/_in_process.py", line 118, in get_requires_for_build_wheel
return hook(config_settings)
^^^^^^^^^^^^^^^^^^^^^
File "/data/data/com.termux/files/usr/tmp/pip-build-env-pa_2_lv3/overlay/lib/python3.11/site-packages/setuptools/build_meta.py", line 338, in get_requires_for_build_wheel
return self._get_build_requires(config_settings, requirements=['wheel'])
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "/data/data/com.termux/files/usr/tmp/pip-build-env-pa_2_lv3/overlay/lib/python3.11/site-packages/setuptools/build_meta.py", line 320, in _get_build_requires
self.run_setup()
File "/data/data/com.termux/files/usr/tmp/pip-build-env-pa_2_lv3/overlay/lib/python3.11/site-packages/setuptools/build_meta.py", line 485, in run_setup
self).run_setup(setup_script=setup_script) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "/data/data/com.termux/files/usr/tmp/pip-build-env-pa_2_lv3/overlay/lib/python3.11/site-packages/setuptools/build_meta.py", line 335, in run_setup
exec(code, locals())
File "", line 6, in
File "/data/data/com.termux/files/usr/lib/python3.11/inspect.py", line 1262, in getsource
lines, lnum = getsourcelines(object)
^^^^^^^^^^^^^^^^^^^^^^
File "/data/data/com.termux/files/usr/lib/python3.11/inspect.py", line 1244, in getsourcelines
lines, lnum = findsource(object)
^^^^^^^^^^^^^^^^^^
File "/data/data/com.termux/files/usr/lib/python3.11/inspect.py", line 1081, in findsource
raise OSError('could not get source code')
OSError: could not get source code
[end of output]

note: This error originates from a subprocess, and is likely not a problem with pip.
error: subprocess-exited-with-error

× Getting requirements to build wheel did not run successfully.
│ exit code: 1 ╰─> See above for output.

note: This error originates from a subprocess, and is likely not a problem with pip.`

最后解决办法就是更新一下wheel就行了:

pip install wheel --upgrade

源于这个discussion: How do I install "playsound" in Python? · termux/termux-app · Discussion #3306 (github.com)

 

 


需要注意的是,使用多进程配合playsound播放音乐时,需要将pygame的初始化至少放在if __name__ == "__main__"这一层下,否则会创建两个窗口。