YouTube教程
https://developers.google.com/youtube/iframe_api_reference?csw=1
后台上传YouTube视频链接,获取这个视屏的时长。
主要代码:
1.获取videoId
// 获取YouTube视频的videoIdfunction matchYoutubeUrl(url) {var p = /^(?:https?:\/\/)?(?:www\.)?(?:youtu\.be\/|youtube\.com\/(?:embed\/|v\/|watch\?v=|watch\?.+&v=))((\w|-){11})(?:\S+)?$/;return (url.match(p)) ? RegExp.$1 : false;}
2.异步引入YouTube提供的api
<script src="https://www.youtube.com/iframe_api"></script>
3.创建YouTube播放器
var player;function onYouTubeIframeAPIReady() {player = new YT.Player('playerYouTube', {height: '360',width: '640',videoId: matchYoutubeUrl('https://www.youtube.com/embed/MYD4kVqxWTY'), // 改变YouTube视频的videoIdevents: {'onReady': onPlayerReady,'onStateChange': onPlayerStateChange}});}
4.当视频播放器准备好时,API将调用这个函数
// 4.当视频播放器准备好时,API将调用这个函数function onPlayerReady(event) {// 视频的时长var YouTubeTime = event.target.getDuration();console.log(YouTubeTime, 'YouTubeTime')event.target.playVideo();}
完整代码:
<body><!-- <iframe width="560" height="315" src="https://www.youtube.com/embed/MYD4kVqxWTY" frameborder="0" allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture" allowfullscreen></iframe> --><!-- 1.<iframe>(和视频播放器)将取代这个<div>标签。 --><div id="playerYouTube"></div><script>// 获取YouTube视频的videoIdfunction matchYoutubeUrl(url) {var p = /^(?:https?:\/\/)?(?:www\.)?(?:youtu\.be\/|youtube\.com\/(?:embed\/|v\/|watch\?v=|watch\?.+&v=))((\w|-){11})(?:\S+)?$/;return (url.match(p)) ? RegExp.$1 : false;}// 2.此代码异步加载IFrame播放器API代码。var tag = document.createElement('script');tag.src = "https://www.youtube.com/iframe_api";var firstScriptTag = document.getElementsByTagName('script')[0];firstScriptTag.parentNode.insertBefore(tag, firstScriptTag);// 3.这个函数创建一个<iframe>(和YouTube播放器)//下载API代码后。var player;function onYouTubeIframeAPIReady() {player = new YT.Player('playerYouTube', {height: '360',width: '640',videoId: matchYoutubeUrl('https://www.youtube.com/embed/MYD4kVqxWTY'), // 改变YouTube视频的videoIdevents: {'onReady': onPlayerReady,'onStateChange': onPlayerStateChange}});}// 4.当视频播放器准备好时,API将调用这个函数function onPlayerReady(event) {// 视频的时长var YouTubeTime = event.target.getDuration();console.log(YouTubeTime, 'YouTubeTime')event.target.playVideo();}var done = false;function onPlayerStateChange(event) {if (event.data == YT.PlayerState.PLAYING && !done) {setTimeout(stopVideo, 6000);done = true;}}function stopVideo() {player.stopVideo();}</script>
</body>