如何通过在JavaScript中构建AudioBuffer来正确播放WAV文件?
How to properly play a WAV file by constructing an AudioBuffer in JavaScript?
我正在努力播放 this WAV file,它在 VLC 中播放(根据它是 Mono
,IMA WAV APDCM Audio (ms)
文件在 24000Hz
采样 16 bits per sample
).
我怀疑WAV文件本身有问题,因为当我尝试通过通过 <audio>
直接嵌入播放时,播放按钮是不活动...当我尝试使用 new Audio()
以编程方式播放它时,我收到错误 Failed to load because no supported source was found.
这是我尝试过的最简单的例子,它产生了 一些 声音……我尝试过的其他尝试在加载时尝试使用 AudioContext.decodeAudioData
全部阻塞音频,抛出 Unable to decode audio data
.
这个例子产生了一些可以辨认的声音,但我显然做错了什么,因为它太刺耳了——我的理解是 AudioBuffer
需要一个 Float32Array
,其值介于 [-1,1]
,这些不是。但我不知道如何规范化它们,因为许多值的顺序是 10e32
.
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<style>
</style>
</head>
<body>
<script>
var context = new AudioContext();
function loadSound(url) {
var request = new XMLHttpRequest();
request.open("GET", url, true);
request.responseType = "arraybuffer";
request.onload = function() {
data = new Uint8Array(request.response);
var buffer = context.createBuffer(1, data.length, 24000);
var channelData = buffer.getChannelData(0);
for (var i = 0; i < data.length; i++) {
channelData[i] = data[i];
}
var source = context.createBufferSource();
source.buffer = buffer;
source.connect(context.destination);
source.start(0);
}
request.send();
}
loadSound('./test.wav');
</script>
</body>
</html>
如有任何帮助,我们将不胜感激;谢谢!
在 this phosphorous
issue 中,我在 readADPCM
和 encodeAudio16bit
函数中找到了合适的答案读取 UInt8Array
并编码 16 位音频。
我正在努力播放 this WAV file,它在 VLC 中播放(根据它是 Mono
,IMA WAV APDCM Audio (ms)
文件在 24000Hz
采样 16 bits per sample
).
我怀疑WAV文件本身有问题,因为当我尝试通过通过 <audio>
直接嵌入播放时,播放按钮是不活动...当我尝试使用 new Audio()
以编程方式播放它时,我收到错误 Failed to load because no supported source was found.
这是我尝试过的最简单的例子,它产生了 一些 声音……我尝试过的其他尝试在加载时尝试使用 AudioContext.decodeAudioData
全部阻塞音频,抛出 Unable to decode audio data
.
这个例子产生了一些可以辨认的声音,但我显然做错了什么,因为它太刺耳了——我的理解是 AudioBuffer
需要一个 Float32Array
,其值介于 [-1,1]
,这些不是。但我不知道如何规范化它们,因为许多值的顺序是 10e32
.
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<style>
</style>
</head>
<body>
<script>
var context = new AudioContext();
function loadSound(url) {
var request = new XMLHttpRequest();
request.open("GET", url, true);
request.responseType = "arraybuffer";
request.onload = function() {
data = new Uint8Array(request.response);
var buffer = context.createBuffer(1, data.length, 24000);
var channelData = buffer.getChannelData(0);
for (var i = 0; i < data.length; i++) {
channelData[i] = data[i];
}
var source = context.createBufferSource();
source.buffer = buffer;
source.connect(context.destination);
source.start(0);
}
request.send();
}
loadSound('./test.wav');
</script>
</body>
</html>
如有任何帮助,我们将不胜感激;谢谢!
在 this phosphorous
issue 中,我在 readADPCM
和 encodeAudio16bit
函数中找到了合适的答案读取 UInt8Array
并编码 16 位音频。