python 使用 sounddevice 输出声音到指定的声卡设备

python 使用 sounddevice 输出声音到指定的声卡设备

python 使用最简单的方式输出音频

这种方式不能指定声音的输出设备,将会使用windows 默认的音频输出进行播放。

这将会使用windows 默认音频输出进行播放。一般是扬声器:

3fa73d52b3fdaba9a8a7bd016a217e5

安装 playsound 模块

from playsound import playsound

temp_play_file='音频文件路径'
# 直接调用方法就能够播放
playsound(temp_play_file)

播放到指定的音频输出设备

参考:https://www.moyann.com/archives/268/

当电脑上有多个音频输出设备,例如耳机、扬声器、显示屏输出设备等。如果需要指定的设备进行播放,此时使用 playsound 方法无法满足要求。

微信截图_20250329122354

需要用到 sounddevice 模块,首先安装:

pip install sounddevice
pip install soundfile

指定设备播放:



import sounddevice as sd
import soundfile as sf


# 下面两个函数, 是根据声卡声道名字, 获取声卡声道名称 及 id, 区分 输出 和 输入 两种声道
def get_input_device_id_by_name(channel_name):
    """
    功能: 根据声卡声道名字, 获取 输入 声道 id
    :return: 返回输入声道id
    """

    devices_list = sd.query_devices()
    for index, device_msg_dict in enumerate(devices_list):
        if channel_name == device_msg_dict["name"] and device_msg_dict["max_input_channels"] > 0:
            return index
    else:
        print("找不到该设备!!!")
        return -1

def get_output_device_id_by_name(channel_name):
    """
    功能: 根据声卡声道名字, 获取 输出 声道 id
    :return: 返回输出声道id
    """

    devices_list = sd.query_devices()
    for index, device_msg_dict in enumerate(devices_list):
        if channel_name == device_msg_dict["name"] and device_msg_dict["max_output_channels"] > 0:
            return index
    else:
        print("找不到该设备!!!")
        return -1
    

def play_audio_with_sounddevice(filename, device=None):
    # 加载音频文件
    data, fs = sf.read(filename, dtype='float32')
    
    # 播放音频
    sd.play(data, fs, device=device)
    sd.wait()  # 等待播放完成

# 列出所有设备
print(sd.query_devices())

# 查找到指定的输出设备
print(get_output_device_id_by_name('耳机 (Realtek(R) Audio)'))

# 选择设备播放 
play_audio_with_sounddevice("test.mp3", device=get_output_device_id_by_name('耳机 (Realtek(R) Audio)'))  # 使用特定设备

python 多个播放设备可以使用

Copyright: 采用 知识共享署名4.0 国际许可协议进行许可

Links: https://zwc365.com/2025/03/29/python-shi-yong-sounddevice-shu-chu-sheng-yin-dao-zhi-ding-de-sheng-ka-she-bei

Buy me a cup of coffee ☕.