需求:APP内页面音频播放时,原生app的返回或者安卓ios的物理键返回返回时,暂停音频播放。
方法:浏览器
标签页被隐藏或显示的时候会触发visibilitychange
事件.点击查看介绍
例子:当你切换到另一个标签时视频会暂停,当你返回到当前标签时视频会再次播放
音频例子
html
<div style="background:#eca2a2;min-height:80px;margin-top:20px;">
<audio id="audio" controls>
<source src="./p3.mp3" type="audio/mp3">
您的浏览器不支持 audio 元素。
</audio>
</div>
js
// 监听页面是否可见
// 设置隐藏属性和改变可见属性的事件的名称
var hidden, visibilityChange;
if (typeof document.hidden !== "undefined") { // Opera 12.10 and Firefox 18 and later support
hidden = "hidden";
visibilityChange = "visibilitychange";
} else if (typeof document.msHidden !== "undefined") {
hidden = "msHidden";
visibilityChange = "msvisibilitychange";
} else if (typeof document.webkitHidden !== "undefined") {
hidden = "webkitHidden";
visibilityChange = "webkitvisibilitychange";
}
var videoElement = document.getElementById("audio");
function handleVisibilityChange() {
if (document[hidden]) {
alert('要关闭')
videoElement.pause();
}
}
当音频是多个的时候
html
<div id="audio-bar">
<audio controls>
<source src="./p3.mp3" type="audio/mp3">
您的浏览器不支持 audio 元素。
</audio>
<audio controls>
<source src="./p3.mp3" type="audio/mp3">
您的浏览器不支持 audio 元素。
</audio>
<audio controls>
<source src="./p3.mp3" type="audio/mp3">
您的浏览器不支持 audio 元素。
</audio>
</div>
js
// 如果页面是隐藏状态,则暂停音频
function handleVisibilityChange() {
// if (document[hidden]) {
// alert('要关闭')
// videoElement.pause();
// } else {
// // videoElement.play();
// }
var domList = document.querySelectorAll('audio');
console.log(domList)
for (var i = 0;i < domList.length;i++) {
domList[i].pause()
}
}
// 如果浏览器不支持addEventListener 或 Page Visibility API 给出警告
if (typeof document.addEventListener === "undefined" || typeof document[hidden] === "undefined") {
console.log("This demo requires a browser, such as Google Chrome or Firefox, that supports the Page Visibility API.");
} else {
// 处理页面可见属性的改变
document.addEventListener(visibilityChange, handleVisibilityChange, false);
}