2015-06-25 76 views
1

是否有方法在HTML5中随时切换音频和视频标签? 这意味着如果同一个信号源以视频开始并选择“关闭视频”,则信号源将被复制到音频标签并继续播放。反过来也是如此。在HTML5中切换音频和视频标签

+0

你这是什么有很多,你有什么尝试? – NewToJS

回答

4

当然 - 只是暂停任何的播放,设定你想创业,并设置新的球员开始元素的<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>