Reputation: 466
I'm trying to play an mp3 file in a WebView. However, the file does not play in the WebView and the page hangs after outputting and error (see log output below).
jQuery code
$.playSound('../static/sounds/cash-register.mp3');
$('#myAudio').on('ended', function() {
window.location.replace("scan_tablet");
});
(function($){
$.extend({
playSound: function(){
return $("<embed src='"+arguments[0]+"' hidden='true' autostart='true' loop='false' class='playSound'>" + "<audio id='myAudio' autoplay='autoplay' style='display:none;' controls='controls'><source src='"+arguments[0]+"' type=\"audio/mpeg\" /><source src='"+arguments[0]+".ogg' type=\"audio/ogg\" /></audio>").appendTo('body');
}
});
})(jQuery);
WebView client
webView.getSettings().setJavaScriptEnabled(true);
webView.getSettings().setJavaScriptCanOpenWindowsAutomatically(true);
webView.getSettings().setDomStorageEnabled(true);
webView.getSettings().setAllowFileAccessFromFileURLs(true);
if (Build.VERSION.SDK_INT >= 19) {
webView.getSettings().setCacheMode(WebSettings.LOAD_NO_CACHE);
}
webView.setWebViewClient(new WebViewClient());
etc...
Log output
1) D/WebViewCallback: shouldInterceptRequest=localhost/static/sounds/cash-register.mp3
2) D/WebViewCallback: onLoadResource=localhost/static/sounds/cash-register.mp3
3) [WARNING:aw_network_delegate.cc(66)] localhost/static/sounds/cash-register.mp3#-3#1
4) E/MediaResourceGetter: Invalid url: java.lang.NumberFormatException: Invalid int: "null"
I'm not sure why the URL appears to be modified in the 3rd line of the Log Output.
When I try this using Chrome on my laptop the mp3 file plays without any issue.
Upvotes: 1
Views: 2006
Reputation: 466
After some further digging around in the WebView documentation, I tried setting the following on the WebView client.
webView.getSettings().setMediaPlaybackRequiresUserGesture(false);
This setting is set to TRUE by default. I think it was preventing the sound from being played.
Upvotes: 2