How to get the mp3 link duration when playing in vlc python?

689 views Asked by At

I was trying to play music from music stored in Firebase Storage using vlc packages. However, when using this packages, we need to define the duration of the time sleep. Error occured when I used urllib.request and mutagen library to retrieve it.

Error

can't sync to MPEG frame
      try:
                    filename, headers = urlretrieve(musicURL)
                    audio = MP3(filename)
                    print(audio.info.length)
                    self.mediaPlayer = vlc.MediaPlayer(musicURL)
                    self.mediaPlayer.play()
                    time.sleep(180)
                    print("Music " + musicName + " is playing")
                    # I not yet find ways to determine music duration from url
                except Exception as e:
                    print(e)
                    pass
3

There are 3 answers

3
AKX On

So, from the comments: instead of trying to use Mutagen, just ask VLC for the duration.

self.mediaPlayer = vlc.MediaPlayer(musicURL)
self.mediaPlayer.play()
duration = self.mediaPlayer.get_length()
print(f"Playing {musicName}")
time.sleep(duration / 1000)  # duration is in milliseconds
0
Wesley On

Just for clarification, I have managed to solve the problem and below is my code:

try:
    self.mediaPlayer = vlc.MediaPlayer(musicURL)
    self.mediaPlayer.play()
    time.sleep(3)
    duration = self.mediaPlayer.get_length()
    self.musicLength = duration/1000

except:
    pass
                        
print(self.musicLength)
self.mediaPlayer.play()
time.sleep(self.musicLength)
print("Music " + musicName + " is playing")
1
luuk hd On

I have a different approach/implementation where you can use VLC but don't have to call media_player.play(). It isn't asynchronous, but it is almost instant anyway.

def get_audio_duration(audio_path):
    # Get audio duration in ms using vlc
    # Works with vlc.__version__ 3.0.1812

    # audio_path: <str> path to an audio file
    # return: <int> audio duration in ms

    media = vlc.Media(audio_path)
    media_player = vlc.MediaPlayer()
    media_player.set_media(media)

    media.parse_with_options(1, 0)
    while media.get_duration() < 0:
        continue
    
    return media.get_duration()