Web Audio API不在设备上播放声音样本,但在浏览器中工作

问题描述:

我有一个Ionic应用程序,它是一个节拍器。使用Web Audio API我已经使用振荡器功能使所有工作都成功,但切换到使用wav文件时,没有音频在真实设备(iPhone)上播放。Web Audio API不在设备上播放声音样本,但在浏览器中工作

在浏览器中使用Ionic Serve(chrome)进行测试时,音频播放正常。

以下是我有:

function snare(e) { 
    var audioSource = 'assets/audio/snare1.wav'; 
    var request = new XMLHttpRequest(); 
    request.open('GET', audioSource, true); 
    request.responseType = 'arraybuffer'; 

    // Decode asynchronously 
    request.onload = function() { 
     audioContext.decodeAudioData(request.response, function(theBuffer) { 
      buffer = theBuffer; 
      playSound(buffer); 
     }); 
    } 
    request.send(); 
} 

function playSound(buffer) { 
    var source = audioContext.createBufferSource(); 
    source.buffer = buffer; 
    source.connect(audioContext.destination); 
    source.start(0); 
} 

的音频采样是通过www /资产/音频。

任何想法可能会出错?

我相信iOS设备需要某种用户手势才能播放音频。

+1

我通常指向人来解决这个问题。基本上,您需要从触摸处理程序调用'AudioBufferSourceNode'上的'start'来“解锁”'AudioContext'。 – padenot

这是2017年7月的iOS 10.3.2,我们仍然在iPhone上的Safari上发现此问题。有趣的是,MacBook上的Safari很好。 @Raymond玩具的一般观察仍然是真实的。但@ padenot的方法(通过https://gist.github.com/laziel/7aefabe99ee57b16081c)在我想要响应某些外部事件/触发器播放声音的情况下对我无效。

使用原来的海报的代码,我已经有一些成功与此

var buffer; // added to make it work with OP's code 

// keep the original function snare() 

function playSound() { // dropped the argument for simplicity. 
    var source = audioContext.createBufferSource(); 
    source.buffer = buffer; 
    source.connect(audioContext.destination); 
    source.start(0); 
} 

function triggerSound() { 

    function playSoundIos(event) { 
     document.removeEventListener('touchstart', playSoundIos); 
     playSound(); 
    } 

    if (/iPad|iPhone/.test(navigator.userAgent)) { 
     document.addEventListener('touchstart', playSoundIos); 
    } 
    else { // Android etc. or Safari, but not on iPhone 
     playSound(); 
    } 
} 

现在呼吁triggerSound()会立即产生Android上的声音,并会产生在iOS声音浏览器的页面已经被感动了。

仍不理想,但总比没有的声音要好......