从 WebView 播放音频
Playing AUDIO from WebView
我一直在寻找如何在 webview 中播放来自任何网站的音频?
我注意到 Chrome 浏览器正在播放音频,但我的 WebView 应用程序无法播放。
你能给我提供任何资源或代码片段吗?
提前致谢!
这可以通过Javascript界面
完成
创建一个Class 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>
试试这个,希望它能解决你的问题。
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
。
我一直在寻找如何在 webview 中播放来自任何网站的音频?
我注意到 Chrome 浏览器正在播放音频,但我的 WebView 应用程序无法播放。 你能给我提供任何资源或代码片段吗?
提前致谢!
这可以通过Javascript界面
完成创建一个Class 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>
试试这个,希望它能解决你的问题。
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
。