Reputation: 1043
I use the simplest instance of WebView and so far everything required works well, except for playing sounds, both javascript invoked sounds and html5 audio tag do not work through this WebView.
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
WebView myWebView = (WebView) findViewById(R.id.webview);
WebSettings webSettings = myWebView.getSettings();
webSettings.setJavaScriptEnabled(true);
myWebView.loadUrl("file:///android_asset/game.html");
}
}
I can exclude issues with the HTML side, since the sound works fine in regular browsers on both PC and phone.
Tested so far on Android 4.4 and Andoroid 7.0 both have sounds within regular browser but no sound within WebView.
Most common answer is that phones require sound to be initiated with a tap on the screen. That does not explain why regular browsers work fine though, while only WebView seems affected.
Upvotes: 12
Views: 17775
Reputation: 61
I faced the same problem and searched a lot for playing audios in android WebViews. My audio files are stored in Google drive. I can play audio files stored in external servers other than Google drive easily using WebViews. But when I want to read it from Google drive, it shows the icon in the WebViews but when I play I get an error "The audio cannot be played". Finally I found a solution in the website https://www.labnol.org/internet/google-drive-mp3-embed/2232/ which is astonishing. He advises to change the last part of the url to 'preview'. For example the url will be of the form https://drive.google.com/file/d/1234ab56/view?usp=sharing, change the last part view?usp=sharing to preview. So finally url will be https://drive.google.com/file/d/1234ab56/preview. And now load it using the same code to load an embedded youtube video in WebView. Thank you.
Upvotes: 0
Reputation: 5577
Try to add this
webSettings.setMediaPlaybackRequiresUserGesture(false)
Upvotes: 30