Reputation: 1779
I've been looking for how to play audio from any website inside the webview?
I've noticed Chrome Browser playing the audio but My WebView app doesn't play. Can you please provide me any resource or code snippet?
Thanks in Advance!
Upvotes: 2
Views: 4648
Reputation: 191
I had the same issue with WebView on Android where audio stopped working when we switched WebView to use HTTPS. Looks like audio doesn't work with HTTPS.
Solution was not to load audio file, it was to include audio file in javascript:
var base64Audio = "data:audio/mpeg;base64,//uQxAAAAAAAAAAAAA";
var dummyAudio = new Audio(base64Audio);
dummyAudio.load();
dummyAudio.play();
Audio as base64 template:
data:audio/mpeg;base64,[MP3_AS_BASE64]
You can use any online encoder to encode audio file to base64.
Upvotes: 0
Reputation: 2879
Try this, hope it solves your problem.
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);
Also, add android:hardwareAccelerated="true"
into activity tag
in manifest.
Upvotes: 2
Reputation: 1
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>
Upvotes: 0