Get youtube file URL from video ID using API

2019-09-13 14:36发布

问题:

I want to reproduce all youtube files embedded on a site using SoundManager2 audio player. How can I get access to Youtube file URL from video ID?

Note: Soundcloud offers the possibility to get the direct streaming URL from the song URL. Here is a working example with Soundmanager2 and Angular. Now I want to do the same for Youtube.

回答1:

One slightly hacky way - You could use Youtube's OEmbed API, however you need to provide a URL, so you'd need to add the ID onto the end. https://www.youtube.com/oembed?url=http%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3DiwGFalTRHDA

This will consistently return an embed iframe, which you could regex the URL out of.

var regex = /<iframe.*?src='(.*?)'/;
var src = regex.exec(str)[1];


回答2:

Your title said using API. It's not possible to get access to YouTube file URL from video ID by that. By mean, with file URL you can also download it, distribute content etc while it's against YouTube Terms. So there is no such API for that.

Since you're tagged with Javascript, there is possibility to get direct access to the file URL. This probably is not as you wanted exactly but it worked flawlessly from the developer tools console available in any browser. For details Here you go

const videoUrls = ytplayer.config.args.url_encoded_fmt_stream_map
  .split(',')
  .map(item => item
    .split('&')
    .reduce((prev, curr) => (curr = curr.split('='),
      Object.assign(prev, {[curr[0]]: decodeURIComponent(curr[1])})
    ), {})
  )
  .reduce((prev, curr) => Object.assign(prev, {
    [curr.quality + ':' + curr.type.split(';')[0]]: curr
  }), {});
console.log(videoUrls);