2016-04-12 75 views

回答

3

Chrome 50發佈:截至2016年4月13日,使用具有MediaStreamAudioSourceNode的分析器節點可以很好地獲取音頻級別。生成的audioLevels值可以是動畫或簡單地傳遞給html meter元素。

var _mediaStream = SOME_LOCAL_OR_RTP_MEDIASTREAM; 
var _audioContext = new AudioContext(); 
var _audioAnalyser = []; 
var _freqs   = []; 
var audioLevels  = [0]; 

var _audioSource   = _audioContext.createMediaStreamSource(_mediaStream); 
var _audioGain1   = _audioContext.createGain(); 
var _audioChannelSplitter = _audioContext.createChannelSplitter(_audioSource.channelCount); 

var _audioSource.connect(_audioGain1); 
var _audioGain1.connect(_audioChannelSplitter); 
var _audioGain1.connect(_audioContext.destination); 

for (let i = 0; i < _audioSource.channelCount; i++) { 
    _audioAnalyser[i]      = _audioContext.createAnalyser(); 
    _audioAnalyser[i].minDecibels   = -100; 
    _audioAnalyser[i].maxDecibels   = 0; 
    _audioAnalyser[i].smoothingTimeConstant = 0.8; 
    _audioAnalyser[i].fftSize    = 32; 
    _freqs[i]        = new Uint8Array(_audioAnalyser[i].frequencyBinCount); 

    _audioChannelSplitter.connect(_audioAnalyser[i], i, 0); 
} 

function calculateAudioLevels() { 
    setTimeout(() => { 
     for (let channelI = 0; channelI < _audioAnalyser.length; channelI++) { 
      _audioAnalyser[channelI].getByteFrequencyData(_freqs[channelI]); 
      let value = 0; 
      for (let freqBinI = 0; freqBinI < _audioAnalyser[channelI].frequencyBinCount; freqBinI++) { 
       value = Math.max(value, _freqs[channelI][freqBinI]); 
      } 
      audioLevels[channelI] = value/256; 
     } 
     requestAnimationFrame(calculateAudioLevels.bind(this)); 
    }, 1000/15); // Max 15fps — not more needed 
} 
+0

雖然有效,但Chrome(自58版起)仍然需要HTML5視頻/音頻元素(無論是否靜音)作爲遠程WebRTC流的端點。如果沒有這個,'createMediaStreamSource(stream)'創建的'MediaStreamAudioSourceNode'只會發出沉默。見:https://bugs.chromium.org/p/chromium/issues/detail?id=121673它說:「需要有一些非WebAudio渲染目標...

0

在JavaScript中,這是實現您想要的唯一方法。