检测音频是否在浏览器 Javascript 中播放 [英] Detect if audio is playing in browser Javascript

查看:44
本文介绍了检测音频是否在浏览器 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?

这里重要的是能够检测任何音频,无论音频来自何处.是否来自 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.

基本上我发现访问整个窗口音频的唯一方法是使用 MediaDevices.getDisplayMedia().

Basically the only way that I found to access the entire window's audio is using MediaDevices.getDisplayMedia().

从那里可以将 MediaStream 输入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 带有 <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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆