gpt4 book ai didi

android - 如何在android中的webview上播放音频?

转载 作者:塔克拉玛干 更新时间:2023-11-03 00:35:24 24 4
gpt4 key购买 nike

我想在 webview 上播放来自 URL 的音频。我还希望它有播放和暂停按钮。我试过像这样直接打开 URL:-

myView = (WebView) findViewById(R.id.webView);
myView.getSettings().setJavaScriptEnabled(true);
myView.loadUrl(myUrl);

但这行不通。

最佳答案

这可以通过 Javascript 接口(interface)完成

创建类 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();
}
}

在您的 WebView 类中

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

在 HTML 代码中

<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>

关于android - 如何在android中的webview上播放音频?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36857146/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com