大约 2 分钟后,Webaudio 声音在 Chrome 停止 Android

Webaudio sound stops on Chrome for Android after about 2 minutes

我 运行 在 Chrome 上为 Android 遇到 WebAudio 问题。

我在三星 Galaxy S3 (GT-I9300) 上遇到此问题:

这是我用来尝试隔离问题的代码:

var audioContext;
if(window.AudioContext) {
    audioContext = new AudioContext();
}

var startTime = Date.now();
var lastTrigger;

var gain = audioContext.createGain();
gain.gain.value = 1;
gain.connect(audioContext.destination);

var buttonTrigger = document.getElementById('trigger');
buttonTrigger.addEventListener('click', function(event) {
    var oscillator =  audioContext.createOscillator();
    oscillator.type = "square";
    oscillator.frequency.value = 100 +  (Math.cos(audioContext.currentTime)*100);
    oscillator.connect(gain);
    oscillator.start(0);
    oscillator.stop(audioContext.currentTime+0.1);

    lastTrigger = Date.now();
});

var timer = document.getElementById('timer');
setInterval(function() {
    if(lastTrigger) { timer.textContent = Date.now() - lastTrigger; }
}, 1000);

这里是 jsfiddle

这只是创建一个振荡器节点并在单击按钮时播放。在我的 phone 上,如果大约一分半钟或两分钟不单击按钮,我将不再听到任何声音。

没有抛出任何错误。

有没有人对这个问题有任何经验和可能的解决方法?

这个问题最初出现在一个更大的应用程序中,该应用程序使用 Phaser 播放 m4a 文件中的声音,因此这不仅仅与振荡器有关。

更新

根据Chromium bug ticket,此问题现已修复。

认为 您看到的是网络音频在一段时间没有声音时自动关闭。如果您第二次单击该按钮(在第一次之后一秒左右),会发生什么? (网络音频可能需要一些时间(至少几十毫秒的数量级)才能重新启动。)

suspend()/resume() 方法和查看 context.state 在这里会有所帮助。

@RaymondToy 的评论回答了这个问题。 Android 上的 Chrome 存在错误(至少三星 Galaxy S3/4 是这样)。 Webaudio 在一段时间不活动后停止播放声音。不活动本质上是沉默。

我能找到的唯一解决方法是每隔一段时间播放某种声音。我尝试过每 30 秒播放一次声音,这样就解决了问题。

我也试过播放某种无声噪音(无声音频缓冲区或 m4a 音频文件的无声部分或静音),都没有解决问题。

在 Android 上遇到同样的问题后。我找到了比每 30 秒播放 "dummy sound" 更好的解决方案。

只要记住你上次在上下文中播放的时间:

var lastPlayed = new Date().getTime();
var audioSource = context.createBufferSource();
    audioSource.connect( context.destination );
    audioSource.buffer = sb;
    audioSource.start( 0 );

下次播放 sample/sound 只需检查经过的时间并重置 AudioContext

if(new Date().getTime()-lastPlayed>30000){   // Time passed since last playing is greater than 30 secs
     context.close();
     context=new AudioContext();
}

对于 Android 这很有魅力。