Load Images and Play Sounds in Java Applets

ava applets can be embedded into a Web page to produce colorful, interactive Web sites. In this article, you will learn to write Java applets that load images and play sounds to give your Web users a true multimedia experience.

Hello World
To start, write a “Hello world” message onto an applet window, which will allow the user to make a picture appear at any point by simply clicking on that point. See the code for this message in Listings 1 (Java) and 2 (HTML).

The init() portion of the code calls a method called getDocumentBase(), which returns the full URL?up to the directory name?of the applet itself. The applet can then load other files that are stored with it, such as an image.

The image filename is passed in as a parameter, so the applet has to call getParameter() to get the filename. Then getImage(), a method built in to the Applet class, is called. GetImage() takes two parameters, a base URL and the image filename, and concatenates them together to give the full URL to the image itself. Because you will store the image in the same directory as the applet on either your hard drive or a Web server, the base URL of the image will be the same as that of the applet?hence the call to getDocumentBase().

GetImage() returns an object of type java.awt.Image, which can hold and display images. Using getImage() will load a picture into the Image object for later use.
(See Sidebar: Parameter Passing in Applets)

Enable the Image to Handle Mouse Clicks
In order to enable the image to respond to mouse events, you need to do two things:

  • Tell your applet to respond to mouse events
  • Write the event handler code for mouse events
  • The first part is simple. Just call addMouseListener at the end of your init() method. This tells the applet that mouse events should be acknowledged, and that your class will process them.

    To write the event handler, your class must implement the MouseListener interface. You can then write a processMouseEvent() method by which you simply save the X and Y coordinates where the user clicks and set a flag called doimg that says the image should appear on the screen. Finally, the event handler uses repaint() to tell the applet to refresh its screen (because the user has clicked the mouse at a specific coordinate and you want the picture to appear at that coordinate).

    The applet also needs to define code for all the other methods defined by the MouseListener interface, namely mouseReleased() through mouseExited(). However, because you don’t need the applet to respond to these events, you can leave their implementation empty.

    Next, comes the paint() method. Like init(), it is defined by the java.applet.Applet class (from which your applet is derived) and is called automatically whenever it is needed. The times it’s needed include when the window first appears on the screen and when another window partially or completely occludes the applet window and then moves away. You can also explicitly force a call to the paint() method by using the applet’s repaint() method as you do in your mouse event handler.

    Paint() is called with a Graphics context g as its argument. You can now use a number of methods in the Graphics class to alter the drawing area. Begin by determining the current size of the applet’s drawing area via a call to getSize(), which returns a Dimension object containing the height and width properties. Then use the drawRect method of the Graphics class to draw a blank rectangle that covers the entire drawing area?this is simply a quick-and-dirty way to clear your drawing area, so you don’t ghost your images when you move the mouse around.

    Next, invite the user to click anywhere. If the class variable doimg is true and the class variable imgnam is not null, then the image retrieved during the init() method will be displayed, followed by the message “Squeak!” in red.

    The method call img.getHeight(this) returns the height of the image. Use the height to calculate the y coordinate of the “Squeak!” string, so that it appears just below your image.

    The Sounds of Multimedia
    Learning how to play sounds will take your program a step closer to true multimedia. Fortunately, Java provides a java.applet.AudioClip class that does all the work for you with its three functions: play(),loop(), and stop().

    As always, you first must make an instance of the AudioClip class before using it in your programs. Also, you can make multiple AudioClip objects and even have them play at the same time if you like. The resulting sound is mixed together to produce a composite. However, depending on your individual sounds, this doesn’t necessarily mean it will be a musical composite.

    Just like with getImage(), you can use a method called getAudioClip(), which the Applet class provides, to load your sound clip into memory. You can see this method in Listing 3 (the HTML code is in Listing 4).

    First, you declare a variable of type AudioClip, letting the user pass in the name of the audio file as a parameter. You did the same with the image. Second, you play your sound when the user clicks the mouse. Sounds play asynchronously, which means the program keeps running while the sound is playing. It doesn’t have to wait for the sound to finish, presenting the appearance that the sound is being played at the same time the picture is being drawn.

    In Listings 3 and 4, notice that you call the audio object’s play() and stop() methods. You need to use play() to play the sound that has been loaded, and the stop() is just a safeguard in case the sound is still playing when the program goes into the event handler again. This can easily happen if the sound clip is long or the user clicks the mouse in very rapid succession.

    Add a Soundtrack
    Now you’re ready for something more complex?adding a soundtrack to play in the background of your applet at the same time. You can see the code in Listing 5 (the HTML code is in Listing 6).

    As you learned previously, multiple AudioClip objects can play at the same time. So, simply make another AudioClip object that loads your soundtrack. Have it start playing right in the applet’s init() method since it doesn’t need to be fired by a specific event (like a mouse click) but rather play from the time the applet is loaded.

    In fact, because you want the soundtrack to play continually, play it with the AudioClip’s loop() method. As you might expect, loop() just plays the sound over and over again, but it has an unexpected catch. The sound will indeed play over and over?even when you leave the Web page containing your applet!

    Let’s put a stop to that behavior! Open a few new Web browser windows (using CTRL-N or New Browser Window from the File menu). Now, open the HTML file in Listing 6, which loads your Java class. Your soundtrack plays and the applet works as expected. Now tell your browser to load, say, http://www.devx.com/. The applet no longer runs, but the jingle keeps playing! Even when you close that browser window, the music doesn’t stop. You have to close every browser window before the tune actually stops.

    This is the only real “gotcha” with the AudioClip object. Make sure you tell the looping sound to stop when your applet closes (using the stop() method). Fortunately, the stop() method is very easy to use. Listing 7 shows you how to do it (see Listing 8 for HTML). The Applet class provides stop(), just as it provides init() and paint(). The program calls this method whenever the applet should close down, whether because the user has moved to a new page or the Web browser is being closed or any other reason. So, in your applet, just call the stop() method of the soundtrack AudioClip object.

    Actually, your chosen sound file may prove to be grating to visitors to your Web site anyway, so you may want to provide an “on/off” toggle button. Simply add a button and use a boolean variable to specify whether the soundtrack is playing or not (see Listing 9 for Java code and Listing 10 for HTML). If it is playing, then you stop it; if it is not, then you start it looping again.

    Applets in Action
    That’s about all there is to adding images and sound to your applets! Click the following links to see?and hear?some examples that demonstrate how your applets will work:

  • Simple Java Applet
  • Simple Java Applet with Audio
  • Simple Java Applet with Looping Audio That StopsWhen User Moves to New Web Page
  • Simple Java Applet with Toggle Button for Turning Soundtrack On and Off
  • Share the Post:
    Share on facebook
    Share on twitter
    Share on linkedin

    Overview

    The Latest

    microsoft careers

    Top Careers at Microsoft

    Microsoft has gained its position as one of the top companies in the world, and Microsoft careers are flourishing. This multinational company is efficiently developing popular software and computers with other consumer electronics. It is a dream come true for so many people to acquire a high paid, high-prestige job

    your company's audio

    4 Areas of Your Company Where Your Audio Really Matters

    Your company probably relies on audio more than you realize. Whether you’re creating a spoken text message to a colleague or giving a speech, you want your audio to shine. Otherwise, you could cause avoidable friction points and potentially hurt your brand reputation. For example, let’s say you create a

    chrome os developer mode

    How to Turn on Chrome OS Developer Mode

    Google’s Chrome OS is a popular operating system that is widely used on Chromebooks and other devices. While it is designed to be simple and user-friendly, there are times when users may want to access additional features and functionality. One way to do this is by turning on Chrome OS