Flash Solution
There is a second way to play sounds at any page, by means of Flash. Several libraries (such as SoundManager 2) provide JavaScript access to Flash objects, and many GWT packages simplify using such libraries, so you won't have to resort to using JSNI. For this example, I opted for the gwt-voices sound library, which proved remarkably easy to use. I could have gone for the GWT SoundManager package, but since it hadn't been updated since 2008, I decided against it.
Download the appropriate package (be careful to match the GWT version you use), and add the JAR file (gwt-voices.jar, for this example) to your GWT project. A sample class using this library is shown in Listing 7. You need to create a SoundController object and then use its createSound() method to create a Sound object that you can play. When you're done with that method, you can destroy it by using the destroySound() method.
Listing 7 Using gwt-voices provides sound for all browsers by using Flash.
package com.fkereki.multimedia.client; import com.allen_sauer.gwt.voices.client.Sound; import com.allen_sauer.gwt.voices.client.SoundController; /** * The gwt-voices library at http://code.google.com/p/gwt-voices/ uses a * small Flash object to actually play sound. The only real problem * might be either a Flash-plugin-less browser, or a browser with an * installed Flash blocker. */ public class GwtVoicesAudioElement extends AudioElement { final SoundController soundController= new SoundController(); final Sound sound; public GwtVoicesAudioElement(final String audioUrl) { super(audioUrl); sound= soundController.createSound(Sound.MIME_TYPE_AUDIO_MPEG, audioUrl); } @Override public void play() { sound.play(); } }
Thanks to our wrapper class, playing a sound with this library is quite easy, and exactly the same as with the other examples (see Listing 8).
Listing 8 Playing a sound through gwt-voices is the same as with the other classes, thanks to our Adapter pattern usage.
final GwtVoicesAudioElement audio3= new GwtVoicesAudioElement("telephone-ring-1.mp3"); final Button playAudioButton3= new Button("Play Audio (Phone) Through gwt_voices"); vp.add(playAudioButton3); playAudioButton3.addClickHandler(new ClickHandler() { @Override public void onClick(final ClickEvent event) { audio3.play(); } });
When you compile a project that uses gwt-voices, a small gwt-voices.swf file (less than 1KB in size) will be included. If the user's browser is set to reject or block Flash objects, no sounds will be produced.