简体   繁体   中英

Playing Audio with QtMultimedia?

Part of a PyQt5 program I'm writing is to take in an audio stream and play it back. 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). I can verify that the MP3 is valid as I can play it in Clementine, VLC, and Dolphin. It was also taken directly from my Plex server, so it's definitely a valid MP3 file. I have tried converting this file to OGG and to WAV with no luck. I have also tried FLAC and AAC audio files and they do not work either.

I saw on a forum that someone suggested running a command to check if PyQt could see any audio devices. 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.

I'm currently running on 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() :

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_())

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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