Ser*_*ran 3 javascript audio wav web-audio-api
我在浏览器上播放PCM Audio时遇到了一些问题.PCM音频来自具有udp协议的Android设备,并以*.raw保存在服务器上
我在webaudioapi的帮助下试图播放这个保存的文件失败了.使用以下代码,播放一些带有白噪声的令人毛骨悚然的声音:
var audioCtx = new (window.AudioContext || window.webkitAudioContext)();
audioCtx.sampleRate = 16000;
// Stereo
var channels = 1;
// Create an empty two second stereo buffer at the
// sample rate of the AudioContext
var frameCount = audioCtx.sampleRate * 10.0;
var myAudioBuffer = audioCtx.createBuffer(channels, frameCount, audioCtx.sampleRate);
var req = new XMLHttpRequest();
req.open('GET', "example.raw", false);
req.overrideMimeType('text\/plain; charset=x-user-defined');
req.send(null);
function play(){
for (var channel = 0; channel < channels; channel++) {
var nowBuffering = myAudioBuffer.getChannelData(channel,16,16000);
for (var i = 0; i < frameCount; i++) {
// audio needs to be in [-1.0; 1.0]
// for this reason I also tried to divide it by 32767
// as my pcm sample is in 16-Bit. It plays still the
// same creepy sound less noisy.
nowBuffering[i] = (req.responseText.charCodeAt(i) & 0xff;
}
}
// Get an AudioBufferSourceNode.
// This is the AudioNode to use when we want to play an AudioBuffer
var source = audioCtx.createBufferSource();
// set the buffer in the AudioBufferSourceNode
source.buffer = myAudioBuffer;
// connect the AudioBufferSourceNode to the
// destination so we can hear the sound
source.connect(audioCtx.destination);
// start the source playing
source.start();
}
Run Code Online (Sandbox Code Playgroud)
它正在播放如此无法识别的声音,我不确定它是否正在播放我认为必须要播放的pcm文件.
我想它必须对pcm文件做一些事情.PCM文件的采样率为16 kHz,每个采样16位,只有一个通道或者更确切地说是单通道.
在这里遇到同样问题的人或有没有人有建议来解决我的问题?
我正在寻找一些解决方案,并感谢任何帮助.
首先:
audioCtx.sampleRate = 16000;不起作用.您无法修改audioCtx.sampleRate.相反,您需要执行以下操作:
var frameCount = req.responseText.length / 2;
var myAudioBuffer = audioCtx.createBuffer(channels, frameCount, 16000);
Run Code Online (Sandbox Code Playgroud)
因为您的文件是16位,所以它的长度(以字节为单位)是您需要的帧数的两倍.
(req.responseText.charCodeAt(i) & 0xff)将产生0到255之间的值,表示单个8位字节.你需要16位.
您需要知道样本的字节顺序,并且每次处理两个字节
对于小端(LSB优先):
var word = (req.responseText.charCodeAt(i * 2) & 0xff) + ((req.responseText.charCodeAt(i * 2 + 1) & 0xff) << 8);
Run Code Online (Sandbox Code Playgroud)
对于大端(MSB优先):
var unsignedWord = ((req.responseText.charCodeAt(i * 2) & 0xff) << 8) + (req.responseText.charCodeAt(i * 2 + 1) & 0xff);
Run Code Online (Sandbox Code Playgroud)
这将产生0到65535之间的数字,表示无符号的16位整数.要转换为有符号整数,您需要执行以下操作(用上面的代码替换X)
var signedWord = (unsignedWord + 32768) % 65536 - 32768;
Run Code Online (Sandbox Code Playgroud)
这将产生介于-32768和32767之间的数字,然后您可以除以32768.0以获得所需的结果.
nowBuffering[i] = signedWord / 32768.0;
Run Code Online (Sandbox Code Playgroud)
编辑:工作示例https://o.lgm.cl/example.html(16位LSB)
| 归档时间: |
|
| 查看次数: |
3655 次 |
| 最近记录: |