javascript - UIWebView 中的 Web Audio API 停止音乐应用程序的当前歌曲

标签 javascript ios uiwebview web-audio-api

Web Audio API 的简单用法:

var UnprefixedAudioContext = window.AudioContext || window.webkitAudioContext;

var context;
var volumeNode;
var soundBuffer;

context = new UnprefixedAudioContext();
volumeNode = context.createGain();
volumeNode.connect(context.destination);
volumeNode.gain.value = 1;

context.decodeAudioData(base64ToArrayBuffer(getTapWarm()), function (decodedAudioData) {
    soundBuffer = decodedAudioData;
});

function play(buffer) {
    var source = context.createBufferSource();
    source.buffer = buffer;
    source.connect(volumeNode);
    (source.start || source.noteOn).call(source, 0);
};

function playClick() {
    play(soundBuffer);
}

UIWebView 中工作正常(播放声音);但是当你切换到音乐应用程序并播放歌曲,然后返回到带有 UIWebView 的应用程序时,歌曲停止播放。

Safari 中相同的代码没有这个问题。

是否有避免这种行为的解决方法?

这是完整的 fiddle :

http://jsfiddle.net/gabrielmaldi/4Lvdyhpx/

最佳答案

您使用的是 iOS 吗?这对我来说听起来像是一个 Audio Session 类别问题。 iOS 应用程序定义了它们的音频与音频的交互方式。来自 Apple's documentation :

Each audio session category specifies a particular pattern of “yes” and “no” for each of the following behaviors, as detailed in Table B-1:

Interrupts non-mixable apps audio: If yes, non-mixable apps will be interrupted when your app activates its audio session.

Silenced by the Silent switch: If yes, your audio is silenced when the user moves the Silent switch to silent. (On iPhone, this switch is called the Ring/Silent switch.)

Supports audio input: If yes, app audio input (recording), is allowed.

Supports audio output: If yes, app audio output (playback), is allowed.

看起来默认类别会静音来自其他应用程序的音频:

AVAudioSessionCategorySoloAmbient—(Default) Playback only. Silences audio when the user switches the Ring/Silent switch to the “silent” position and when the screen locks. This category differs from the AVAudioSessionCategoryAmbient category only in that it interrupts other audio.

这里的关键在最后一句:“它中断了其他音频”。

根据您是否希望在屏幕锁定时将音频静音等,您可以使用许多其他类别。AVAudioSessionCategoryAmbient 不会使音频静音。

在您应用的 objective-c 部分尝试一下:

NSError *setCategoryError = nil;

BOOL success = [[AVAudioSession sharedInstance]
                setCategory: AVAudioSessionCategoryAmbient
                      error: &setCategoryError];

if (!success) { /* handle the error in setCategoryError */ }

关于javascript - UIWebView 中的 Web Audio API 停止音乐应用程序的当前歌曲,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28593303/

相关文章:

ios - UIWebView 没有立即停止

javascript - Google Maps API '.pac-item:first' 返回格式错误

javascript - 模板文字内的事件回调

ios - 如何在单个 UIView 中启用两个不同 UIScrollview 的缩放?

javascript - 如何在IOS浏览器中设置网站cookie?

javascript - 以编程方式在 UIWebview 中填充数据

javascript - 在 Angular 项目中获取正确的 URL

javascript - 简单的表单提交文件

objective-c - 从 NSMutableArray 的元素中检查 0 作为整数值

iOS KeyChain secItemAdd 崩溃