在vlc python中播放时如何获取mp3链接持续时间?

vlurs2pr  于 2023-04-10  发布在  Python
关注(0)|答案(3)|浏览(144)

我尝试使用vlc包从Firebase Storage中存储的音乐播放音乐。但是使用此包时,需要定义睡眠时间的持续时间。使用urllib.requestmutagen库检索时出错。

错误

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
bvjveswy

bvjveswy1#

所以,从评论来看:而不是试图使用诱变剂,只是问VLC的持续时间。

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
3phpmpom

3phpmpom2#

只是为了澄清,我已经设法解决了这个问题,下面是我的代码:

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")
iyfamqjs

iyfamqjs3#

我有一个不同的方法/实现,你可以使用VLC,但 * 不必调用media_player.play() *。它不是异步的,但它几乎是即时的。

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

相关问题