Search code examples
pythonpyqtpyqt5audio-playerqtmultimedia

pyqt5 looping mp3 file


I want to loop an audio file and using a combination of THIS CODE (my orignal question with solution) and THIS CODE (Qt C example) managed to create this:

from PyQt5.QtCore import *
from PyQt5.QtMultimedia import *
import sys

if __name__ == "__main__":

    app = QCoreApplication(sys.argv)

    playlist = QMediaPlaylist()
    url = QUrl.fromLocalFile("./sound2.mp3")
    playlist.addMedia(url)
    playlist.setPlaybackMode(QMediaPlaylist.Loop)

    content = playlist()
    player = QMediaPlayer()
    player.setMedia(content)
    player.play()

    app.lastWindowClosed.connect(player.stop)
    app.exec()

However, this code does not work and the error reported is:

TypeError: arguments did not match any overloaded call: addMedia(self, QMediaContent): argument 1 has unexpected type 'QUrl' addMedia(self, object): argument 1 has unexpected type 'QUrl'

Where am I going wrong with the code? Any help is most appreciated.


Solution

  • You were close. Try the following...

    playlist = QMediaPlaylist()
    url = QUrl.fromLocalFile("./sound2.mp3")
    playlist.addMedia(QMediaContent(url))
    playlist.setPlaybackMode(QMediaPlaylist.Loop)
    
    player = QMediaPlayer()
    player.setPlaylist(playlist)
    player.play()