【问题标题】:Web Audio API not playing sound sample on device, but works in browserWeb Audio API 不在设备上播放声音样本,但在浏览器中工作
【发布时间】:2017-04-13 10:02:41
【问题描述】:

我有一个 Ionic 应用程序,它是节拍器。使用 Web Audio API,我使用振荡器功能使一切正常工作,但是当切换到使用 wav 文件时,没有音频在真实设备 (iPhone) 上播放。

在使用 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/assets/audio。

有什么想法可能会出错吗?

【问题讨论】:

    标签: ios audio ionic-framework web-audio-api


    【解决方案1】:

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

    【讨论】:

    • 我通常将人们指向 gist.github.com/laziel/7aefabe99ee57b16081c> 来解决这个问题。基本上,您需要从触摸处理程序调用AudioBufferSourceNode 上的start 以“解锁”AudioContext
    【解决方案2】:

    现在是 2017 年 7 月,iOS 10.3.2,我们仍然在 iPhone 上的 Safari 上发现这个问题。有趣的是,MacBook 上的 Safari 很好。 @Raymond Toy 的一般观察似乎仍然正确。但是@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上产生声音。

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-08-30
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多