1

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.

Kenly
  • 24,317
  • 7
  • 44
  • 60
Eamonn
  • 658
  • 1
  • 7
  • 22

1 Answers1

4

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_())
eyllanesc
  • 235,170
  • 19
  • 170
  • 241
  • Could you please check [this](https://stackoverflow.com/questions/67661657/python-pyqt5-how-to-play-an-audio-file-through-a-custom-method?fbclid=IwAR0do7CSDBrAM8K4SGy31nr0n0sDey_FGb5kNeW3KgC9ZOwy9YObppA4xT8) – Ishara Madhawa May 23 '21 at 16:08