从WebView

时间:2017-03-27 14:01:40

标签: android webview audio-player

我一直在寻找如何从网页浏览中的任何网站播放音频?

我注意到Chrome浏览器播放音频,但我的WebView应用程序无法播放。 能否请您提供任何资源或代码段?

提前致谢!

2 个答案:

答案 0 :(得分:0)

这可以通过Javascript接口

完成

创建一个WebInterface类

public class WebInterface{
    Context mContext;

    WebInterface(Context c) {
        mContext = c;
    }

    @JavascriptInterface
    public void playSound(String toast) {
        Toast.makeText(mContext, toast, Toast.LENGTH_SHORT).show();
    }

    @JavascriptInterface
    public void pauseSound(String toast) {
        Toast.makeText(mContext, toast, Toast.LENGTH_SHORT).show();
    }
}
In your WebView class

WebView browser;
browser=(WebView)findViewById(R.id.webkit);   
browser.getSettings().setJavaScriptEnabled(true);
browser.addJavascriptInterface(new WebInterface(this), "Android");        
browser.loadUrl("http://someurl.com");
In HTML code

<html>
<head>
<script type="text/javascript">
    function playSound(toast) {
        Android.showToast(toast);
    }

    function pauseSound(toast) {
        Android.showToast(toast);
    }
</script>
</head>
<body>
<input type="button" value="Say hello" onClick="playSound('Sound Played!')" />
<input type="button" value="Say hello" onClick="pauseSound('Sound Paused!')" />
</body>
</html>

答案 1 :(得分:0)

试试这个,希望它能解决你的问题。

WebView webView = findViewById(R.id.webview);
webView.setWebViewClient(new WebViewClient());
WebSettings webSettings = webView.getSettings();
webSettings.setJavaScriptEnabled(true);
webSettings.setAllowContentAccess(true);
webSettings.setDomStorageEnabled(true);
webView.loadUrl(url);

另外,将android:hardwareAccelerated="true"添加到清单中的activity tag