SoundApplet.java Source code

Java tutorial

Introduction

Here is the source code for SoundApplet.java

Source

/* From http://java.sun.com/docs/books/tutorial/index.html */
/*
 * Copyright (c) 2006 Sun Microsystems, Inc. All Rights Reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions are met:
 *
 * -Redistribution of source code must retain the above copyright notice, this
 *  list of conditions and the following disclaimer.
 *
 * -Redistribution in binary form must reproduce the above copyright notice,
 *  this list of conditions and the following disclaimer in the documentation
 *  and/or other materials provided with the distribution.
 *
 * Neither the name of Sun Microsystems, Inc. or the names of contributors may
 * be used to endorse or promote products derived from this software without
 * specific prior written permission.
 *
 * This software is provided "AS IS," without a warranty of any kind. ALL
 * EXPRESS OR IMPLIED CONDITIONS, REPRESENTATIONS AND WARRANTIES, INCLUDING
 * ANY IMPLIED WARRANTY OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE
 * OR NON-INFRINGEMENT, ARE HEREBY EXCLUDED. SUN MIDROSYSTEMS, INC. ("SUN")
 * AND ITS LICENSORS SHALL NOT BE LIABLE FOR ANY DAMAGES SUFFERED BY LICENSEE
 * AS A RESULT OF USING, MODIFYING OR DISTRIBUTING THIS SOFTWARE OR ITS
 * DERIVATIVES. IN NO EVENT WILL SUN OR ITS LICENSORS BE LIABLE FOR ANY LOST
 * REVENUE, PROFIT OR DATA, OR FOR DIRECT, INDIRECT, SPECIAL, CONSEQUENTIAL,
 * INCIDENTAL OR PUNITIVE DAMAGES, HOWEVER CAUSED AND REGARDLESS OF THE THEORY
 * OF LIABILITY, ARISING OUT OF THE USE OF OR INABILITY TO USE THIS SOFTWARE,
 * EVEN IF SUN HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES.
 *
 * You acknowledge that this software is not designed, licensed or intended
 * for use in the design, construction, operation or maintenance of any
 * nuclear facility.
 */
import java.applet.AudioClip;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.ItemEvent;
import java.awt.event.ItemListener;
import java.net.URL;

import javax.swing.JApplet;
import javax.swing.JButton;
import javax.swing.JComboBox;
import javax.swing.JPanel;

public class SoundApplet extends JApplet implements ActionListener, ItemListener {
    AppletSoundList soundList;

    String auFile = "spacemusic.au";

    String aiffFile = "flute+hrn+mrmba.aif";

    String midiFile = "trippygaia1.mid";

    String rmfFile = "jungle.rmf";

    String wavFile = "bottle-open.wav";

    String chosenFile;

    AudioClip onceClip, loopClip;

    JComboBox formats;

    JButton playButton, loopButton, stopButton;

    boolean looping = false;

    public void init() {
        String[] fileTypes = { auFile, aiffFile, midiFile, rmfFile, wavFile };
        formats = new JComboBox(fileTypes);
        formats.setSelectedIndex(0);
        chosenFile = (String) formats.getSelectedItem();
        formats.addItemListener(this);

        playButton = new JButton("Play");
        playButton.addActionListener(this);

        loopButton = new JButton("Loop");
        loopButton.addActionListener(this);

        stopButton = new JButton("Stop");
        stopButton.addActionListener(this);
        stopButton.setEnabled(false);

        JPanel controlPanel = new JPanel();
        controlPanel.add(formats);
        controlPanel.add(playButton);
        controlPanel.add(loopButton);
        controlPanel.add(stopButton);
        getContentPane().add(controlPanel);

        startLoadingSounds();
    }

    public void itemStateChanged(ItemEvent e) {
        chosenFile = (String) formats.getSelectedItem();
        soundList.startLoading(chosenFile);
    }

    void startLoadingSounds() {
        //Start asynchronous sound loading.
        soundList = new AppletSoundList(this, getCodeBase());
        soundList.startLoading(auFile);
        soundList.startLoading(aiffFile);
        soundList.startLoading(midiFile);
        soundList.startLoading(rmfFile);
        soundList.startLoading(wavFile);
    }

    public void stop() {
        onceClip.stop(); //Cut short the one-time sound.
        if (looping) {
            loopClip.stop(); //Stop the sound loop.
        }
    }

    public void start() {
        if (looping) {
            loopClip.loop(); //Restart the sound loop.
        }
    }

    public void actionPerformed(ActionEvent event) {
        //PLAY BUTTON
        Object source = event.getSource();
        if (source == playButton) {
            //Try to get the AudioClip.
            onceClip = soundList.getClip(chosenFile);
            onceClip.play(); //Play it once.
            stopButton.setEnabled(true);
            showStatus("Playing sound " + chosenFile + ".");
            if (onceClip == null) {
                showStatus("Sound " + chosenFile + " not loaded yet.");
            }
            return;
        }

        //START LOOP BUTTON
        if (source == loopButton) {
            loopClip = soundList.getClip(chosenFile);

            looping = true;
            loopClip.loop(); //Start the sound loop.
            loopButton.setEnabled(false); //Disable loop button.
            stopButton.setEnabled(true);
            showStatus("Playing sound " + chosenFile + " continuously.");
            if (loopClip == null) {
                showStatus("Sound " + chosenFile + " not loaded yet.");
            }
            return;
        }

        //STOP LOOP BUTTON
        if (source == stopButton) {
            if (looping) {
                looping = false;
                loopClip.stop(); //Stop the sound loop.
                loopButton.setEnabled(true); //Enable start button.
            } else if (onceClip != null) {
                onceClip.stop();
            }
            stopButton.setEnabled(false);
            showStatus("Stopped playing " + chosenFile + ".");
            return;
        }
    }
}

//Loads and holds a bunch of audio files whose locations are specified
//relative to a fixed base URL.

class AppletSoundList extends java.util.Hashtable {
    JApplet applet;

    URL baseURL;

    public AppletSoundList(JApplet applet, URL baseURL) {
        super(5); //Initialize Hashtable with capacity of 5 entries.
        this.applet = applet;
        this.baseURL = baseURL;
    }

    public void startLoading(String relativeURL) {
        new AppletSoundLoader(applet, this, baseURL, relativeURL);
    }

    public AudioClip getClip(String relativeURL) {
        return (AudioClip) get(relativeURL);
    }

    public void putClip(AudioClip clip, String relativeURL) {
        put(relativeURL, clip);
    }
}

class AppletSoundLoader extends Thread {
    JApplet applet;

    AppletSoundList soundList;

    URL baseURL;

    String relativeURL;

    public AppletSoundLoader(JApplet applet, AppletSoundList soundList, URL baseURL, String relativeURL) {
        this.applet = applet;
        this.soundList = soundList;
        this.baseURL = baseURL;
        this.relativeURL = relativeURL;
        setPriority(MIN_PRIORITY);
        start();
    }

    public void run() {
        AudioClip audioClip = applet.getAudioClip(baseURL, relativeURL);
        soundList.putClip(audioClip, relativeURL);
    }
}