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

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

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

相关标签:
9条回答
  • 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 <audio> 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 <audio> element src
          var youtubeAudio = document.getElementById('youtube');
          youtubeAudio.src = audioURL;
          
        });
      }
    });
    
    function parse_str(str) {
      return str.split('&').reduce(function(params, param) {
        var paramSplit = param.split('=').map(function(value) {
          return decodeURIComponent(value.replace('+', ' '));
        });
        params[paramSplit[0]] = paramSplit[1];
        return params;
      }, {});
    }
    <audio id="youtube" controls></audio>

    0 讨论(0)
  • 2020-12-02 12:08

    I agree with Tom van der Woerdt. You could use CSS to hide the video (visibility:hidden or overflow:hidden in a div wrapper constrained by height), but that may violate Youtube's policies. Additionally, how could you control the audio (pause, stop, volume, etc.)?

    You could instead turn to resources such as http://www.houndbite.com/ to manage audio.

    0 讨论(0)
  • 2020-12-02 12:10

    VIDEO_ID with actual ID of your YouTube video.

    <div data-video="VIDEO_ID"  
            data-autoplay="0"         
            data-loop="1"             
            id="youtube-audio">
     </div>
    
     <script src="https://www.youtube.com/iframe_api"></script>
     <script src="https://cdn.rawgit.com/labnol/files/master/yt.js"></script>
    
    0 讨论(0)
提交回复
热议问题