Search code examples
python-3.xyoutubevlcpython-vlc

How to play youtube videos in python-vlc?


import vlc

p = vlc.MediaPlayer("https://www.youtube.com/watch?v=7ailmFB38Rk")
p.play()

gives me this error

[00007f97a80030c0] http stream error: local stream 1 error: Cancellation (0x8)

I was told this is causes if the link is invalid or broken, both of these are not the cases because using regular vlc to play the video works perfectly

Also, if it is somehow not possible to play the video, I only need to play the audio so that will also be of help.


Solution

  • use pafy

    
    # importing vlc module 
    import vlc 
      
    # importing pafy module 
    import pafy 
      
    # url of the video 
    url = "https://www.youtube.com/watch?v = vG2PNdI8axo"
      
    # creating pafy object of the video 
    video = pafy.new(url) 
      
    # getting best stream 
    best = video.getbest() 
      
    # creating vlc media player object 
    media = vlc.MediaPlayer(best.url) 
      
    # start playing video 
    media.play()