Earlier today, I came across a problem. I have been working on an App in Android that displays HTML5 files from the assets folder inside a
WebView. One of the big problems with playing Audio in an HTML5 page is that a lot of browsers do not support the
<audio>tag; this includes several versions of the
WebViewcontrol in different versions of Android. The bottom line is that you can't expect standardized results across different versions of Android when using the HTML5
<audio>tag. So we're going to use a workaround that uses the native Android method of playing audio.
Here is a synopsis of the paragraphs below that describe how to implement the code.
Implementing the Code
Configuring your WebView control
WebViewcontrol inside your layout. This is the XML code for the layout I used:
This is the Java that I used to initially configure the
Creating an Audio Interface for the HTML5 web page
Next, we're going to create an
AudioInterfaceJava class to play audio MP3s from the assets folder.
Create a new Java Class and call it "
Here is the Java code for the class:
The above code creates a
publicmethod that accepts a
stringargument which is used as the URL for the mp3 file location. So I store my mp3 files in a sub folder in the assets folder called audio. So the playAudio method needs an argument similar to this: "audio/example.mp3". If it was stored directly in the assets folder it would look like this: "example.mp3".
Attaching the Audio Interface to the WebView control
Now, we need to attach the
AudioInterfaceclass to the
WebViewcontrol in the
onCreatemethod we edited earlier in the layout's Java file:
Now we can call the
And that's it, it's kind of an annoying work around but at least you know it will work rather than waiting on the
<audio>kinks to be worked out.