在HTML5中切换音频和视频标签

时间:2015-06-25 00:22:56

标签: javascript jquery html5 webrtc

有没有办法在HTML5中动态切换音频和视频标签? 这意味着如果相同的源以视频开头并选择“视频关闭”,则源将被复制到音频标签并继续播放。反过来也是这样。

1 个答案:

答案 0 :(得分: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>