简体   繁体   English

用 QtMultimedia 播放音频?

[英]Playing Audio with QtMultimedia?

Part of a PyQt5 program I'm writing is to take in an audio stream and play it back.我正在编写的 PyQt5 程序的一部分是接收音频流并播放它。 I've searched around and this is the code I have found that is said to work:我四处搜索,这是我发现的据说可以工作的代码:

url = QtCore.QUrl.fromLocalFile('office theme.mp3')
content = QtMultimedia.QMediaContent(url)
player = QtMultimedia.QMediaPlayer()
player.setMedia(content)
player.play()

However, this does not work for me.但是,这对我不起作用。 I have tried putting the code in a variety of places (after the window.show() call, inside and outside of various classes I have, etc).我尝试将代码放在各种位置(在window.show()调用之后,我拥有的各种类的内部和外部等)。 I can verify that the MP3 is valid as I can play it in Clementine, VLC, and Dolphin.我可以验证 MP3 是否有效,因为我可以在 Clementine、VLC 和 Dolphin 中播放它。 It was also taken directly from my Plex server, so it's definitely a valid MP3 file.它也是直接从我的 Plex 服务器上获取的,因此它绝对是一个有效的 MP3 文件。 I have tried converting this file to OGG and to WAV with no luck.我曾尝试将此文件转换为 OGG 和 WAV,但没有成功。 I have also tried FLAC and AAC audio files and they do not work either.我也试过 FLAC 和 AAC 音频文件,但它们也不起作用。

I saw on a forum that someone suggested running a command to check if PyQt could see any audio devices.我在论坛上看到有人建议运行命令来检查 PyQt 是否可以看到任何音频设备。 I ran the following code and it returned multiple audio output devices:我运行了以下代码,它返回了多个音频输出设备:

print(QtMultimedia.QAudioDeviceInfo.availableDevices(QtMultimedia.QAudio.AudioOutput))

All I need to do is take in a reference to an audio file (eventually opened from a file dialogue, but I'll cross that bridge when I come to it) and play it.我需要做的就是引用一个音频文件(最终从文件对话中打开,但当我来到它时我会穿过那座桥)并播放它。 Am I doing it incorrectly?我做错了吗? I am by no means an expert on PyQt and have been experimenting for a couple of days only.我绝不是 PyQt 的专家,并且只进行了几天的实验。

I'm currently running on Antergos Arch Linux.我目前在 Antergos Arch Linux 上运行。

You have to pass the complete path, but if you want to just pass the name of the file and that the program adds the rest you can use QDir::current() :您必须传递完整路径,但如果您只想传递文件名并且程序添加其余部分,您可以使用QDir::current()

import sys

from PyQt5 import QtCore, QtWidgets, QtMultimedia

if __name__ == '__main__':
    app = QtWidgets.QApplication(sys.argv)
    filename = 'office theme.mp3'
    fullpath = QtCore.QDir.current().absoluteFilePath(filename) 
    url = QtCore.QUrl.fromLocalFile(fullpath)
    content = QtMultimedia.QMediaContent(url)
    player = QtMultimedia.QMediaPlayer()
    player.setMedia(content)
    player.play()
    sys.exit(app.exec_())

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM