javascript - HTML Web Audio API - 左右声道的音频可视化

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

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

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

这是我的代码:

<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>

Audio signal level meter

最佳答案

使用createScriptProcessor(2048, 2, 2)拥有两个输入 channel 和两个输出 channel 。然后,在 onaudioprocess 内,第二个输入 channel 数据将位于 evt.inputBuffer.getChannelData(1) 中。

请注意:

  • 创建 audioContext 后,您可能需要存储(或检查)inChannels = audioContext.destination.channelCountoutChannels = audioContext.destination.channelCount
  • processor.bufferSize 的值为 2048 适合数据可视化,但考虑到 16384 的音频质量会更好

关于javascript - HTML Web Audio API - 左右声道的音频可视化,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51961711/

相关文章:

javascript - null 在 xhr 请求中发送了期望的文件内容

javascript - 动画 HTML 列表下一个/上一个固定长度

html - 选定选项的背景样式

html - Font Awesome 图标对齐

html - 可视化网站中页面链接层次结构的网站

audio - 网络(非?)流音频解决方案?

javascript - 在 Angular 中通过选项卡利用 ui-router

javascript - 导出 react redux connect 时出现 Flow uncovered 代码警告

css - 为什么可见性不适用于 div?

javascript - Service Worker 和页面权限