I want to play an audio from a URL on webview. I also want it to have play and pause button. I have tried opening the URL directly like this:-
myView = (WebView) findViewById(R.id.webView);
myView.getSettings().setJavaScriptEnabled(true);
myView.loadUrl(myUrl);
But this isn't working.
This can be done through Javascript Interface
Create a 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>
Try, this is the working code,
WebView mWebView;
mWebView = (WebView)findViewById(R.id.webView);
// Enable Javascript
WebSettings webSettings = mWebView.getSettings();
webSettings.setJavaScriptEnabled(true);
mWebView.loadUrl("http://www.stephaniequinn.com/Music/Allegro%20from%20Duet%20in%20C%20Major.mp3");
// Force links and redirects to open in the WebView instead of in a browser
mWebView.setWebViewClient(new WebViewClient());
i tried with one sample audio url. it should work.
Happy Coding..!!!
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With