检测音频是否在浏览器Javascript中播放 [英] Detect if audio is playing in browser Javascript
问题描述
是否存在一种全局方法来检测音频何时在浏览器中播放或开始播放.
Is there a global way to detect when audio is playing or starts playing in the browser.
类似if(window.mediaPlaying()){...
没有将代码绑定到特定元素吗?
without having the code tied to a specific element?
这里重要的是无论音频来自哪里,都能够检测 ANY 音频.无论是来自iframe,视频,Web Audio API等等.
What's important here is to be able to detect ANY audio no matter where the audio comes from. Whether it comes from an iframe, a video, the Web Audio API, etc.
推荐答案
没有人可以使用它,但是它可以工作.
No one should use this but it works.
Basically the only way that I found to access the entire window's audio is using MediaDevices.getDisplayMedia().
从此处可以将 MediaStream 放入<一个href ="https://developer.mozilla.org/en-US/docs/Web/API/AnalyserNode" rel ="noreferrer"> AnyalizerNode 可用于检查音频音量是否更大大于零.
From there a MediaStream can be fed into an AnyalizerNode that can be used to check the if the audio volume is greater than zero.
仅在Chrome浏览器中有效也许还有Edge (仅在Linux上的Chrome 80中经过测试)
Only works in Chrome and maybe Edge (Only tested in Chrome 80 on Linux)
JSFiddle 和<video>
,<audio>
和YouTube!
JSFiddle with <video>
, <audio>
and YouTube!
重要的代码段(由于片段iframe上的功能政策):
Important bits of code (cannot post in a working snippet because of the Feature Policies on the snippet iframe):
var audioCtx = new AudioContext();
var analyser = audioCtx.createAnalyser();
var bufferLength = analyser.fftSize;
var dataArray = new Float32Array(bufferLength);
window.isAudioPlaying = () => {
analyser.getFloatTimeDomainData(dataArray);
for (var i = 0; i < bufferLength; i++) {
if (dataArray[i] != 0) return true;
}
return false;
}
navigator.mediaDevices.getDisplayMedia({
video: true,
audio: true
})
.then(stream => {
if (stream.getAudioTracks().length > 0) {
var source = audioCtx.createMediaStreamSource(stream);
source.connect(analyser);
document.body.classList.add('ready');
} else {
console.log('Failed to get stream. Audio not shared or browser not supported');
}
}).catch(err => console.log("Unable to open capture: ", err));
这篇关于检测音频是否在浏览器Javascript中播放的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!