How to play only the audio of a Youtube video using HTML 5?

前端 未结 9 620
花落未央
花落未央 2020-12-02 11:17

Is it possible to play only the audio from a YouTube video using HTML 5 and Javascript?

9条回答
  •  慢半拍i
    慢半拍i (楼主)
    2020-12-02 12:08

    UPDATED FOR 2020

    It seems in Septeber 2019, YouTube updated the values that are returned by get_video_info.

    Rather than data.url_encoded_fmt_stream_map and data.adaptive_fmts (as used in the other older examples) now we are looking for for data.formats and dataadaptiveFormats.

    Anyways here is what you are all here for some code that loads a YouTube video into an element. Try it on CodePen

    // YouTube video ID
    var videoID = "CMNry4PE93Y";
    
    // Fetch video info (using a proxy if avoid CORS errors)
    fetch('https://cors-anywhere.herokuapp.com/' + "https://www.youtube.com/get_video_info?video_id=" + videoID).then(response => {
      if (response.ok) {
        response.text().then(ytData => {
          
          // parse response to find audio info
          var ytData = parse_str(ytData);
          var getAdaptiveFormats = JSON.parse(ytData.player_response).streamingData.adaptiveFormats;
          var findAudioInfo = getAdaptiveFormats.findIndex(obj => obj.audioQuality);
          
          // get the URL for the audio file
          var audioURL = getAdaptiveFormats[findAudioInfo].url;
          
          // update the 

提交回复
热议问题