Android - 确定Web视图是否播放声音

Fou*_*Fou 8 android webview

webview中加载的网页是在后台自动播放,我想检测声音何时停止而不是显示toast信息.

谢谢

cod*_*zjx 12

如果你使用它,这很容易JavascriptInterface.按照我的步骤:

1.创建一个接口回调:

public class MediaWebInterface {

    public MediaWebInterface() {

    }

    @JavascriptInterface
    public void setEndedIndex(int pIndex) {
        // Call when the audio ended.
    }

}
Run Code Online (Sandbox Code Playgroud)

2.创建包含"已结束"侦听器的javascript:

<script type='text/javascript'>window.onload=function(){var n=document.getElementsByTagName("audio"),r=n.length;for(var o=0;o<r;o++)n[o].setAttribute("index",o),n[o].addEventListener("ended",function(){for(var e=0;e<r;e++)this===n[e]&&window.external.setEndedIndex(e)})}
</script>
Run Code Online (Sandbox Code Playgroud)

3.将html数据加载到一个并附加到Stringjavascript以上的html数据String:

// Enable javascript support
mWebView.getSettings().setJavaScriptEnabled(true); 
mWebView.addJavascriptInterface(new MediaWebInterface(mHandler), "external");
mWebView.loadDataWithBaseURL(mBaseURL, mHTMLData+aboveJavascript, null, "utf-8", null);
Run Code Online (Sandbox Code Playgroud)

4.当音频停止时,它将调用MediaWebInterface.setEndedIndex(pIndex),而pIndex是音频的索引.

Hava乐趣,试试吧!

请先阅读WebView.addJavascriptInterface()!

警告:如果你使用proguard,你应该将跟随脚本添加到你的proguard-project.txt.否则,回调将无效.因为类名和方法会混淆,所以javascript无法回调.

//Preserved javaScript interface class
-keepclassmembers class com.xxx.xxx.javascript.MediaWebInterface {
   public *;
}
Run Code Online (Sandbox Code Playgroud)