Play audio with PyQt5

If in playAudioFile is performed, icon has changed but play() method dosen’t work. Every time the condition is false.

This code works in some files, but I can’t see a rule. Format files and file’s long doesn’t matter. I tried with .wav, .mp3 and .mp4 for a try.

In windows player every files work.

import sys
import os
from PyQt5.QtCore import QUrl
from PyQt5.uic import loadUi
from PyQt5.QtWidgets import QApplication, QStackedWidget, QMainWindow, QStyle
from PyQt5.QtMultimedia import QMediaPlayer, QMediaContent

class Term2(QMainWindow):

    def __init__(self):
        super().__init__()
        loadUi('screen2.ui', self)

        # create player
        self.player = QMediaPlayer()
        self.choose_music()
        self.btn_play.clicked.connect(self.playAudioFile)

    # play audio
    def choose_music(self):
        filepath = os.path.join(os.getcwd(), 'pc.wav')
        url = QUrl.fromLocalFile(filepath)
        content = QMediaContent(url)
        self.player.setMedia(content)
        print(filepath)

    def playAudioFile(self):
        if self.player.state() == QMediaPlayer.PlayingState:
            self.player.pause()
            self.btn_play.setIcon(
                self.style().standardIcon(QStyle.SP_MediaPlay)
            )
        else:
            self.player.play()
            self.btn_play.setIcon(
                self.style().standardIcon(QStyle.SP_MediaPause)
            )

app = QApplication(sys.argv)
widget = QStackedWidget()
t2 = Term2()
widget.setWindowTitle('Project)
widget.setFixedWidth(700)
widget.setFixedHeight(400)
widget.addWidget(t2)
widget.show()
sys.exit(app.exec_())

I created button in Qt Designer and import in loadUi('screen2.ui', self)

>Solution :

I would use an audio player from a different library, that one appears quite old. I would recommend looking into playsound or the pygame audio mixer.
Playsound works like this:

from playsound import playsound
playsound(path_to_audio_file)

It is quite limited in abilities, but is simple, reliable, and works with all mp3 and wav formats. Here is a tutorial: https://www.geeksforgeeks.org/play-sound-in-python/

If you want something a little more advanced I would try out pygames audio mixer, you can play stuff, control volumes, timings and more. At its most basic:

from pygame import mixer

mixer.init()
mixer.music.load(path_to_audio_file)
mixer.music.play()

The best format for the mixer is wav, but others would probably work.
A tutorial for this one:
https://www.geeksforgeeks.org/python-playing-audio-file-in-pygame/

Leave a Reply