Search code examples
pythonpyqtpyqt6

in pyqt6,how to play audio?


I want to play a .mp3 audio file, I have seen the documentation.
the documentation writes the below code.

player = QMediaPlayer()
audioOutput = QAudioOutput()
player.setAudioOutput(audioOutput)
connect(player, SIGNAL(positionChanged(qint64)), self, SLOT(positionChanged(qint64)))
player.setSource(QUrl.fromLocalFile("/Users/me/Music/coolsong.mp3"))
audioOutput.setVolume(50)
player.play()

and below is my code.

        self.player = QMediaPlayer()
        self.setup_listener()
        audio = QAudioOutput()
        self.player.setAudioOutput(audio)
        filename = '1111.mp3'
        fullpath = QDir.current().absoluteFilePath(filename)
        url = QUrl.fromLocalFile(fullpath)
        self.player.setSource(url)
        self.player.play()

        print(self.player.hasAudio())  # true
        print(self.player.isPlaying())  # true

I ensure the above two sentences print all print true,
but I did not hear any voice.
What's wrong with my code?
Thanks all.

I have tried to use other .mp3 files and use an absolute path, but no voice appears.


Solution

  • Try keeping a reference to the QAudioOutput object by storing it as a instance attribute, as well as the QMediaPlayer. I think what might be happening is the audio output is being garbage collected after the class constructor is exits.

    For example

        self.player = QMediaPlayer()
        self.audio = QAudioOutput()
        self.player.setAudioOutput(self.audio)
        self.player.setSource(...)
        self.player.play()