我找到了解决方案。 Pygame v2 使这一切成为可能。由于pygame使用sdl2,我们可以通过pygame自己实现的sdl2库来获取音频设备名称。
更新方法
关于 pygame 的最新版本;
获取音频设备名称:
import pygame
import pygame._sdl2.audio as sdl2_audio
def get_devices(capture_devices: bool = False) -> Tuple[str, ...]:
init_by_me = not pygame.mixer.get_init()
if init_by_me:
pygame.mixer.init()
devices = tuple(sdl2_audio.get_audio_device_names(capture_devices))
if init_by_me:
pygame.mixer.quit()
return devices
并通过特定设备播放音频文件:
from time import sleep
import pygame
def play(file_path: str, device: Optional[str] = None):
if device is None:
devices = get_devices()
if not devices:
raise RuntimeError("No device!")
device = devices[0]
print("Play: {}\r\nDevice: {}".format(file_path, device))
pygame.mixer.init(devicename=device)
pygame.mixer.music.load(file_path)
pygame.mixer.music.play()
try:
while True:
sleep(0.1)
except KeyboardInterrupt:
pass
pygame.mixer.quit()
老方法
在 pygame v2 的早期版本上;
获取音频设备名称:
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()