简体   繁体   English

在HTML5中的音频和视频标签之间切换

[英]Switch between audio and video tags in HTML5

Is there a way to switch between the audio and video tags in HTML5 on the fly? 有没有一种方法可以在HTML5中即时切换音频和视频标签? Meaning that if the same source starts with video and selects "video off", the source will be copied over to the audio tag and resume playing. 这意味着如果同一源以视频开头并选择“视频关闭”,则该源将被复制到音频标签并继续播放。 Same thing with the other way around. 反之亦然。

Sure - just pause whatever's playing, set the <source> on the element you want to start, and set the new player to begin where the other left off: 当然-只需暂停所有正在播放的内容,在要开始的元素上设置<source> ,然后将新播放器设置为从另一个停止播放的位置开始:

 var playing = "video"; var audio = document.getElementById("audio"); var video = document.getElementById("video"); var source = document.createElement("source"); source.setAttribute("src", "http://vjs.zencdn.net/v/oceans.mp4"); source.setAttribute("id", "sourceElement"); video.appendChild(source); video.play(); document.getElementById("toggleAV").onclick = function(e) { switch (playing) { case "video": video.pause(); video.setAttribute("class", "hidden"); video.removeChild(source); audio.appendChild(source); audio.currentTime = video.currentTime; audio.setAttribute("class", ""); audio.play(); playing = "audio"; break; case "audio": audio.pause(); audio.setAttribute("class", "hidden"); audio.removeChild(source); video.appendChild(source); video.currentTime = audio.currentTime; video.setAttribute("class", ""); video.play(); playing = "video"; break; } }; 
 html, body { height: 100%; width: 100%; } .hidden { display: none; } 
 <!DOCTYPE html> <html> <head> <meta charset=utf-8 /> <title>so</title> <meta name='viewport' content='initial-scale=1,maximum-scale=1,user-scalable=no' /> </head> <body> <video id="video" width="320" height="240" controls></video> <audio id="audio" controls class="hidden"></audio> <button id="toggleAV">Toggle AV</button> </body> </html> 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM