How to stream audio from a Youtube URL in Python (without download)?

后端 未结 2 1662
面向向阳花
面向向阳花 2020-12-05 08:45

I have been trying to create a way to stream a youtube url (preferably audio only, although this doesn\'t matter too much) right from python code. I have tried numerous thin

2条回答
  •  一生所求
    2020-12-05 09:34

    pafy according to its documentation do not list playing media directly (at least I didn't find any).

    However we can use it to get correct url, and then use player such as vlc to play directly without downloading.

    You can download vlc from here

    First we get correct / best URL from youtube using pafy

    import pafy
    import vlc
    
    url = "https://www.youtube.com/watch?v=bMt47wvK6u0"
    video = pafy.new(url)
    best = video.getbest()
    playurl = best.url
    

    Over here playurl is best URL to play. Then we use VLC to play it.

    Instance = vlc.Instance()
    player = Instance.media_player_new()
    Media = Instance.media_new(playurl)
    Media.get_mrl()
    player.set_media(Media)
    player.play()
    

    This will open a window with no controls (play/pause/stop etc). You can run these command on the repr window or at python prompt (depending upon how you are using it)
    You will need to build one accordingly using vlc commands such as

    >>> player.pause() #-- to pause video
    >>> player.resume()  #-- resume paused video.
    >>> player.stop()  #-- to stop/end video
    

提交回复
热议问题