【发布时间】:2022-03-01 14:24:30
【问题描述】:
我需要使用 pygame 通过不同的音频设备播放音频文件。显然,这可以通过方法pygame.mixer.init() 中的参数devicename 实现,但没有相关文档。
我的问题:
1- 如何设置 pygame 混音器的输出设备(或通道/声音,如果可能)?
2- 如何列出所有可用的设备名称?
【问题讨论】:
我需要使用 pygame 通过不同的音频设备播放音频文件。显然,这可以通过方法pygame.mixer.init() 中的参数devicename 实现,但没有相关文档。
我的问题:
1- 如何设置 pygame 混音器的输出设备(或通道/声音,如果可能)?
2- 如何列出所有可用的设备名称?
【问题讨论】:
我找到了解决方案。 Pygame v2 使这一切成为可能。由于pygame使用sdl2,我们可以通过pygame自己实现的sdl2库来获取音频设备名称。
获取音频设备名称:
import pygame._sdl2 as sdl2
pygame.init()
is_capture = 0 # zero to request playback devices, non-zero to request recording devices
num = sdl2.get_num_audio_devices(is_capture)
names = [str(sdl2.get_audio_device_name(i, is_capture), encoding="utf-8") for i in range(num)]
print("\n".join(names))
pygame.quit()
在我的设备上,代码返回:
HDA Intel PCH, 92HD87B2/4 Analog
HDA Intel PCH, HDMI 0
C-Media USB Headphone Set, USB Audio
并为 pygame 混音器设置输出音频设备:
import pygame
import time
pygame.mixer.pre_init(devicename="HDA Intel PCH, 92HD87B2/4 Analog")
pygame.mixer.init()
pygame.mixer.music.load("audio.ogg")
pygame.mixer.music.play()
time.sleep(10)
pygame.mixer.quit()
【讨论】:
使用sounddevice python包查询设备名称。
import sounddevice
devs = sounddevice.query_devices()
print(devs) # Shows current output and input as well with "<" abd ">" tokens
for dev in devs:
print(dev['name'])
在 Windows 10 2020.04 上,这些名称似乎具有以下格式
()
其中 name 是您可以更改的内容,而控制器名称是驱动程序的显示名称。 例如。我的三星电视音频输出(通过 hdmi)名称是:
SAMSUNG TV 1(2- AMD 高清音频设备)
请注意,打印查询结果本身似乎有一个奇怪的表示,例如我得到了我当前的音频输出:
显然没有全名。
【讨论】:
只是更新@h.nodehi 的答案,以帮助像我一样努力实现此功能的任何人。
Current Package Version: pygame 2.1.2 (SDL 2.0.18, Python 3.9.10)
Tested Systems: Windows 10 (21H2 - 19044.1288), Ubuntu (20.04.3 LTS)
获取音频设备列表:
mixer.init() # Initialize the mixer, this will allow the next command to work
print(sdl2.audio.get_audio_device_names(False)) # Returns playback devices, Boolean value determines whether they are Input or Output devices.
mixer.quit() # Quit the mixer as it's initialized on your main playback device
例如,我的设备返回:
['Speakers (High Definition Audio Device)', 'CABLE Input (VB-Audio Virtual Cable)']
然后,播放音频:
mixer.init(devicename = 'Speakers (High Definition Audio Device)') # Initialize it with the correct device
mixer.music.load("Toby Fox - Megalovania.mp3") # Load the mp3
mixer.music.play() # Play it
while mixer.music.get_busy(): # wait for music to finish playing
time.sleep(1)
如果您想连续播放多个曲目,请将以下代码段添加到上面的 while 循环中:
...
else:
mixer.music.unload() # Unload the mp3 to free up system resources
mixer.music.load("Sleeping at Last - Saturn.wav") # Load the wav
...
如果您使用的是较新版本的软件包,并且列出的某些方法由于 AttributeError: module 'pygame' has no attribute {method_name} 而似乎不起作用,请使用 pyup 并搜索相关方法,看看是否有对方法调用方式的任何更改。这是@h.nodehi 的代码 sn-p 不再有效的主要原因,除非您使用旧版本的 pygame。
【讨论】: