【问题标题】:HTML Web Audio API - audio visualisation of left & right channelsHTML Web Audio API - 左右声道的音频可视化
【发布时间】:2019-01-28 09:52:14
【问题描述】:

我是网络音频 API 的新手。我需要可视化播放音频的左右声道信号强度,如下图所示。

evt.inputBuffer.getChannelData(0) 将返回整个通道信息,我将如何获取左右通道数据,我应该在哪里更改我的代码?请帮忙。

这是我的代码:

<style>
   #meter1, #meter2 {
   width: 0%;
   height: 15px;
   margin: 2px 0;
   background: green;
   }
</style>

<div style="width: 250px;">
   <div id="meter1"></div>
</div>
<div style="width: 250px;">
   <div id="meter2"></div>
</div>
<script>
   // Create the audio context - AudioContext is a little container where all our sound will live. 
   //It provides access to the Web Audio API, which in turn gives us access to some very powerful functions.
   // Browser support
   window.AudioContext = window.AudioContext || window.webkitAudioContext;
   // Initialize audio context
   var audioContext = new AudioContext();

   var soundUrl = "sample.mp3";
   var soundBuffer; 

   var audio = new Audio(soundUrl);
   var processor = audioContext.createScriptProcessor(2048, 1, 1), meter1 = document.getElementById('meter1'), meter2 = document.getElementById('meter2'), source, splitter;
   audio.crossOrigin = 'anonymous'

   audio.addEventListener('canplaythrough', function(){
   //create a new MediaElementAudioSourceNode object, given an existing HTML <audio> or <video> element, the audio from which can then be played and manipulated.    
   source = audioContext.createMediaElementSource(audio)
   splitter = audioContext.createChannelSplitter(2);
   source.connect(splitter);
   source.connect(processor)
   source.connect(audioContext.destination)
   processor.connect(audioContext.destination)

   audio.play()
   console.log(source);
   }, false);


   // loop through PCM data and calculate average
   // volume for a given 2048 sample buffer
   processor.onaudioprocess = function(evt){
   //console.log(evt.inputBuffer);
   var input = evt.inputBuffer.getChannelData(0)
     , len = input.length   
     , total = i = 0
     , rms
   while ( i < len ) total += Math.abs( input[i++] )
   rms = Math.sqrt( total / len )
   meter1.style.width = ( rms * 100 ) + '%'
   }

</script>

【问题讨论】:

  • evt.inputBuffer.getChannelData(1) 获取其他通道(如果有)

标签: javascript html web web-audio-api javascript-audio-api


【解决方案1】:

使用createScriptProcessor(2048, 2, 2) 有两个输入通道和两个输出通道。那么在onaudioprocess内,第二个输入通道的数据就会在evt.inputBuffer.getChannelData(1)内。

注意:

  • 创建audioContext 后,您可能需要存储(或检查)inChannels = audioContext.destination.channelCount 和outChannels = audioContext.destination.channelCount
  • processor.bufferSize 的值 2048 有利于数据可视化,但考虑到 16384 对音频质量更好

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-07-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-01-01
    • 2020-11-04
    • 1970-01-01
    相关资源
    最近更新 更多