chaNcharge
chaNcharge

Reputation: 237

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.

Upvotes: 1

Views: 1379

Answers (2)

Skandix
Skandix

Reputation: 1994

regarding your error, the traceback says everthing:

argument 1 has unexpected type 'QMediaContent'

looking at the documentation we see

void QStatusBar::showMessage(const QString &message, int timeout = 0)

that it expects a QString or simply str in python -> build a string:

self.statusBar().showMessage(str(self.playlist.currentMedia()))

but wait, their is more!
Did you know that you don't need a lambda-function to connect your function:

self.playlist.currentMediaChanged.connect(self.songChanged) # <- no brackets

also currentMediaChanged does provide the current QMediaContent - docs:

void QMediaPlayer::currentMediaChanged(const QMediaContent &media)

meaning you can make your songChanged-function a bit smaller:

def songChanged(self, media):
  if media:
    print(media)
    self.statusBar().showMessage(str(media))

to get the file's name from the object you can use: media.canonicalUrl().fileName()

 print(media.canonicalUrl().fileName())
 self.statusBar().showMessage(str(media.canonicalUrl().fileName()))

Upvotes: 1

eyllanesc
eyllanesc

Reputation: 244013

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())

Upvotes: 1

Related Questions