How to use HTML5 audio tag with GWT


In a nutshell, GWT and the html5 audio tag work very well with one another. It’s a rather simple matter to interface with the audio tag through strategic use of JSNI (JavaScriptNativeInterface). Basically, JSNI means that you can get your Javascript all up in your Java. This is really just a short JSNI tutorial disguised as an audio tag tutorial, so I’ll show you how to use JSNI and then how to interact with the audio tag through Javascript.

JSNI

Now, JSNI is incredibly simple to use. Here’s an example of JSNI in action:

public class audiotutorial implements EntryPoint { 

public void onModuleLoad() { callSomeJavascript(); }
public native void callSomeJavascript()/*-
{
 //This is Javascript.
alert("Flax.ie, for science."); }-*/;
 }

Note the “native” and the fact that the method body is actually commented out and ended with a semicolon. That’s it. That’s all you need to write Javascript inside GWT. Your Javascript functions can return values as normal, and you can pass values in as normal also.Easy, right? Interfacing with the audio tag is almost easier.

Audio Tag

First, you’ll have to modify your html to, you know, have an audio tag in it.
Something like this:


And then you’ll need to make a JSNI method somewhere in your code like so:

public native void playAudioTag() /*-{
$doc.getElementById('audioTag').play();
//$doc and $wnd are JSNI-speak for document and window
}-*/;

Job done. You can, of course, use any built-in function for audio here also.


For more information on JSNI (I really recommend you read this, I’ve only scratched the surface), read this. For more information on the audio tag, read here.

About the Author

Carl Lange

I'm currently a Computer Games Development student at Carlow IT. I love programming and all things technical, and I'll learn anything if it's interesting. I'm passionate about technical education, and naturally about games. Check out my resume, and follow me on Twitter!

Visit Website

One Comment

  1. Can this be done without the audio tag in the HTML? (In my case, I want to add a number sound effects to my GWT game).

    Or do I need a bunch of audio tags, one for each sound I wish to play?

    Is the audio loaded each time it’s called, do you know?

    I’ve no idea of JavaScript, only Java…

    Thanks.

Leave a Comment

Your email address will not be published. Required fields are marked *

*