首页 > 解决方案 > PyQt5 选择要播放的音频设备输出

问题描述

这个简单的代码将有一个 GUI 按钮,当按下该按钮时,将播放example.mp3到默认的音频输出设备。

import sys
from PyQt5 import QtCore, QtMultimedia
from PyQt5.QtMultimedia import QAudio, QAudioDeviceInfo
from PyQt5.QtWidgets import QApplication, QWidget, QPushButton, QComboBox


class SimplePlay(QWidget):
    def __init__(self):
        super().__init__()
        self.player = QtMultimedia.QMediaPlayer()
        url = QtCore.QUrl.fromLocalFile(QtCore.QDir.current().absoluteFilePath("example.mp3"))
        self.sound_file = QtMultimedia.QMediaContent(url)

        button = QPushButton("Play", self)
        button.clicked.connect(self.on_click)

        self.combo_box_devices = QComboBox(self)
        self.combo_box_devices.setGeometry(0, 50, 300, 50)
        for device in QAudioDeviceInfo.availableDevices(QAudio.AudioOutput):
            self.combo_box_devices.addItem(device.deviceName())

        self.show()

    def on_click(self):
        self.player.setMedia(self.sound_file)
        self.player.play()


if __name__ == '__main__':
    app = QApplication(sys.argv)
    ex = SimplePlay()
    sys.exit(app.exec_())

有没有办法用代码指定它将播放到哪个音频设备输出?或者以某种方式设置播放器默认输出设备。

具体示例是拥有 2 个播放设备、扬声器和耳机。假设扬声器是系统的默认输出设备,我怎么能播放耳机而不是扬声器?我需要能够用代码改变它。

正如您在上面的代码中看到的,有一个组合框列出了所有输出设备。我想当您单击时,根据您选择的组合框条目,它会播放到该选定的设备。

- 更新 -

基于 Chiku1022 answerI 我设法做到了:

    scv: QtMultimedia.QMediaService = self.player.service()
    out: QtMultimedia.QAudioOutputSelectorControl = scv.requestControl("org.qt-project.qt.audiooutputselectorcontrol/5.0")
    out.setActiveOutput(self.combo_box_devices.currentText())
    scv.releaseControl(out)
    scv = self.player.service()

    out = scv.requestControl("org.qt-project.qt.audiooutputselectorcontrol/5.0")
    out.setActiveOutput(self.combo_box_devices.currentText())

    scv.releaseControl(out)

combo_box_devices 中的字符串只是scv.availableOutputs()

尽管如此,有人暗示将 QT_MULTIMEDIA_PREFERRED_PLUGINS 设置为 windowsmediafoundation 对我不起作用,将其保留为默认的 DirectShow 工作。

标签: pythonpython-3.xaudiopyqt5qtmultimedia

解决方案


Qt5+ 如何为 QMediaPlayer 设置默认音频设备

这是您正在寻找的。它在 C++ 中,所以你需要想出 python 的出路。它不是那么困难。我目前不在我的电脑上,否则我会在这里编写 python 代码。

更新

os.environ['QT_MULTIMEDIA_PREFERRED_PLUGINS'] = 'windowsmediafoundation'

在代码顶部添加上面的代码行。这将帮助您的媒体播放器使用 windows 的最新媒体 API 而不是 DirectShow,因此 QAudioDeviceInfo 将正常工作。


推荐阅读