为 pygame 混音器设置输出设备

h.n*_*ehi 6 python audio pygame

我需要使用 pygame 通过不同的音频设备播放音频文件。显然,这可以通过pygame.mixer.init()devicename方法中的参数实现,但没有相关文档。

我的问题:

1- 如何设置 pygame 混音器的输出设备(如果可能,或通道/声音)?

2- 如何列出所有可用的设备名称?

h.n*_*ehi 3

我找到了解决方案。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
Run Code Online (Sandbox Code Playgroud)

并通过特定设备播放音频文件:

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()
Run Code Online (Sandbox Code Playgroud)

老方法

在 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()
Run Code Online (Sandbox Code Playgroud)

在我的设备上,代码返回:

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
Run Code Online (Sandbox Code Playgroud)

并设置 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()
Run Code Online (Sandbox Code Playgroud)