Search code examples
pythonpyqtpyqt5qmediaplayerqmediacontent

PyQt5 - Return currently playing media name from QMediaPlaylist currentMedia() function


I have this code in a function:

self.playlist.currentMediaChanged.connect(lambda: self.songChanged())

and it calls this function:

def songChanged(self):
    if self.playlist.mediaCount != 0:
        print(QMediaContent(self.playlist.currentMedia()))
        self.statusBar().showMessage(self.playlist.currentMedia())

Printing it returns

<PyQt5.QtMultimedia.QMediaContent object at 0x109458cf8>

And trying to show it in the status bar returns an error:

TypeError: showMessage(self, str, msecs: int = 0): argument 1 has unexpected type 'QMediaContent'

How can I get the program to return the currently playing file name or song title in the playlist as a string to put in the status bar? Sorry if this is a dumb question, I'm still learning PyQt.


Solution

  • You do not have to connect the function evaluated to the signal, only the name of the function. The currentMediaChanged signal returns the current QMediaContent, then you must use that QMediaContent and get the QUrl, and then as I showed in my previous answer we get the following:

        self.playlist.currentMediaChanged.connect(self.songChanged)
    
    def songChanged(self, media):
        if not media.isNull():
            url = media.canonicalUrl()
            self.statusBar().showMessage(url.fileName())