webview里的背景音乐,在退出时,怎么关闭
发布于 5 年前 作者 yinchao 18235 次浏览 来自 问答

小程序里使用里webview组件,组件里放的网页有背景音乐。当退出小程序时,这个背景音乐还在播放。能否有办法做到,当退出小程序,背景音乐就没有了?

6 回复

你好,怎么解决的

请问使用pagehide问题解决了吗?

可以在h5的pagehide事件里,暂停音乐

微信小程序退出的时候关闭web-view  H5的音乐代码如下:

(function () {

 
                    var hidden = "hidden";
  
                    //各个浏览器属性兼容
                    if (hidden in document)
                        document.addEventListener("visibilitychange", onchange);
                    else if ((hidden = "mozHidden"in document)
                        document.addEventListener("mozvisibilitychange", onchange);
                    else if ((hidden = "webkitHidden"in document)
                        document.addEventListener("webkitvisibilitychange", onchange);
                    else if ((hidden = "msHidden"in document)
                        document.addEventListener("msvisibilitychange", onchange);
  
                    else if ("onfocusin" in document)
                        document.onfocusin = document.onfocusout = onchange;
  
                    else
                        window.onpageshow = window.onpagehide = window.onfocus = window.onblur = onchange;
  
                    //主要功能代码
                    //网页状态改变事件
                    function onchange(evt) {
                        if (document[hidden]) {
                            $('#audio').removeClass('play');
                            document.getElementById("bgm").pause();
//                            document.title = "false";
                        else {
//                            alert('显示');
                            setTimeout(function () {
                                $('#audio').addClass('play');
                                document.getElementById("bgm").play();
//                                document.title = "true";
                            },100);
                        }
                    }
  
  
                    if (document[hidden] !== undefined)
                        onchange({
                            type: document[hidden] ? "blur" "focus"
                        });

                })();


我也遇到了这个问题,ios下关闭小程序还会继续播放视频(其实你下滑状态栏可以看到有视频播放,不关闭会一直播放的),最后用了浏览器的visibilitychange 解决了(后台时暂停播放),具体代码如下。

var hiddenProperty = 'hidden' in document ? 'hidden' :
    'webkitHidden' in document ? 'webkitHidden' :
    'mozHidden' in document ? 'mozHidden' :

     null;


if (hiddenProperty) {

    var visibilityChangeEvent = hiddenProperty.replace(/hidden/i, 'visibilitychange');

    var onVisibilityChange = function() {

    if (document[hiddenProperty]) {

        !MpMovie.video.paused && MpMovie.video.pause();

    }

};


document.addEventListener(visibilityChangeEvent, onVisibilityChange);

相关资料

https://developer.mozilla.org/zh-CN/docs/Web/Events/visibilitychange

回到顶部