转换Web Audio API中的采样率

时间:2016-04-10 03:03:29

标签: javascript web-audio

如何在浏览器中将缓冲区的采样率从44100转换为48000?

我找到了一个库https://github.com/taisel/XAudioJS/blob/master/resampler.js,应该允许我这样做,但不知道如何使用它。

2 个答案:

答案 0 :(得分:2)

使用离线音频上下文。以下内容可能有效:

var c = new OfflineAudioContext(1, len, 48000);
var b = c.createBuffer(1, len, 44100);
b.copyToChannel(yourSourceBuffer, 0);
var s = c.createBufferSource();
s.buffer = b;
s.connect(context.destination);
s.start();
c.startRendering().then(function (result) {
  // result contains the new buffer resampled to 48000
});

根据实施情况,重采样信号的质量可能会有很大差异。

答案 1 :(得分:1)

当音频上下文的采样率与音频文件的采样率不同时,移动Safari中似乎没有错误地解码加载的音频。此外,音频上下文的采样率通常会从44100随机变为48000,但并不总是取决于网站是否在开启或关闭iPhone声音的情况下加载。

此问题的解决方法是读取音频上下文的采样率,然后为每个采样率加载不同的音频文件,如下所示:

window.AudioContext = window.AudioContext || window.webkitAudioContext;
var audio_context = new AudioContext();
var actual_sample_rate = audio_context.sampleRate;
if (actual_sample_rate != 48000) {
    actual_sample_rate = 44100;
}

function finished_loading_sounds(sounds) {
    buffers['piano_do'] = {
        buffer: sounds.piano,
        rate: 1
    };
    // ...do something when the sounds are loaded...
}

var buffer_loader = new BufferLoader(
    audio_context,
    {
        piano: "audio/" + actual_sample_rate + "/piano.m4a",
    },
    finished_loading_sounds
);

buffer_loader.load();

缓冲加载器的定义与this tutorial中的相同。

要更改音频文件的采样率,可以使用Audacity

<强>更新

似乎即使您尝试使用正确的采样率加载文件,有时在iOS设备上声音仍然会失真。

要解决此问题,I found a hack for your AudioContext

function createAudioContext(desiredSampleRate) {
    var AudioCtor = window.AudioContext || window.webkitAudioContext;

    desiredSampleRate = typeof desiredSampleRate === 'number'
        ? desiredSampleRate
        : 44100;
    var context = new AudioCtor();

    // Check if hack is necessary. Only occurs in iOS6+ devices
    // and only when you first boot the iPhone, or play a audio/video
    // with a different sample rate
    if (/(iPhone|iPad)/i.test(navigator.userAgent) && context.sampleRate !== desiredSampleRate) {
        var buffer = context.createBuffer(1, 1, desiredSampleRate);
        var dummy = context.createBufferSource();
        dummy.buffer = buffer;
        dummy.connect(context.destination);
        dummy.start(0);
        dummy.disconnect();

        context.close(); // dispose old context
        context = new AudioCtor();
    }
    return context;
}

然后使用它,按如下方式创建音频上下文:

var audio_context = createAudioContext(44100);