uni-app中 uni.createInnerAudioContext()创建的音频播放会被uni.previewImage()暂停

uni-app中 uni.createInnerAudioContext()创建的音频播放会被uni.previewImage()暂停

4 回复

未复现此问题,用示例代码hello uni-app 使用uni.previewImage()能出现你的问题吗? 【咨询问题/bug处理优先级规则】:https://ask.dcloud.net.cn/article/38139

更多关于uni-app中 uni.createInnerAudioContext()创建的音频播放会被uni.previewImage()暂停的实战教程也可以访问 https://www.itying.com/category-93-b0.html


示例工程会出现此问题,请在体验版小程序或真实小程序环境调试,即可复现,小程序模拟器为正常播放不会被中断。 在真实小程序环境中,uni.previewImage会使uniapp版小程序进入App Hide,即播放音乐被暂停,关闭previewImage,播放即恢复。

问题出现在,uni.previewImage会使程序进入AppHide,而uni.createInnerAudioContext()不会在后台播放,后台播放使用的是uni.getBackgroundAudioManager()。请勿指导使用BackgroundAudio替换InnerAudio,项目需求非后台播放,现已采用自定义preview,替换uni.previewImage,来曲线解决问题,但依旧希望能弄明白,uni.previewImage会进入AppHide事件的原理。

uni-app 中,uni.createInnerAudioContext() 创建的音频播放确实会被 uni.previewImage() 暂停。这是因为 uni.previewImage() 会打开一个全屏的图片预览界面,而全屏操作通常会触发系统的默认行为,导致其他音频播放被暂停。

解决方案

  1. 监听 uni.previewImage 的生命周期事件: 你可以在 uni.previewImage 打开时暂停音频播放,并在预览关闭时恢复播放。

    const innerAudioContext = uni.createInnerAudioContext();
    
    innerAudioContext.src = 'your-audio-url';
    innerAudioContext.play();
    
    uni.previewImage({
        urls: ['your-image-url'],
        success: () => {
            innerAudioContext.pause(); // 预览图片时暂停音频
        },
        fail: () => {
            // 处理失败情况
        },
        complete: () => {
            innerAudioContext.play(); // 预览结束后恢复音频
        }
    });
    
  2. 使用 onHideonShow 监听应用生命周期: 如果 uni.previewImage 导致音频暂停,你可以通过监听应用的生命周期事件来恢复音频播放。

    const innerAudioContext = uni.createInnerAudioContext();
    
    innerAudioContext.src = 'your-audio-url';
    innerAudioContext.play();
    
    uni.onAppHide(() => {
        innerAudioContext.pause(); // 应用进入后台时暂停音频
    });
    
    uni.onAppShow(() => {
        innerAudioContext.play(); // 应用回到前台时恢复音频
    });
回到顶部