PyQt5 select 将播放哪个音频设备输出

PyQt5 select which audio device output will play

这个简单的代码将有一个 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的回答我做到了:

    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 即可。

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

更新

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

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