Kamis, 10 Januari 2013

How to Play WAV Audio / Sound File with Java

Here is Java source code to play WAV audio / Sound play. There are two files; SoundEffect.java and SoundEffectDemo.java. SoundEffect file is enum and SoundEffectDemo is GUI based program which use SoundEffect enum.

SoundEffect.java

import java.io.*;
import java.net.URL;
import javax.sound.sampled.*;

public enum SoundEffect {

    EXPLODE("explode.wav"), // explosion
    GONG("gong.wav"), // gong
    SHOOT("shoot.wav"); // bullet

    public static enum Volume {
        MUTE, LOW, MEDIUM, HIGH
    }

    public static Volume volume = Volume.LOW;
    // Each sound effect has its own clip, loaded with its own sound file.
    private Clip clip;

    // Constructor to construct each element of the enum with its own sound file.
    SoundEffect(String soundFileName) {
        try {
            // Use URL (instead of File) to read from disk and JAR.
            URL url = this.getClass().getClassLoader().getResource(soundFileName);
            // Set up an audio input stream piped from the sound file.
            AudioInputStream audioInputStream = AudioSystem.getAudioInputStream(url);
            // Get a clip resource.
            clip = AudioSystem.getClip();
            // Open audio clip and load samples from the audio input stream.
            clip.open(audioInputStream);
        } catch (UnsupportedAudioFileException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } catch (LineUnavailableException e) {
            e.printStackTrace();
        }
    }

    // Play or Re-play the sound effect from the beginning, by rewinding.
    public void play() {
        if (volume != Volume.MUTE) {
            if (clip.isRunning()) {
                clip.stop();   // Stop the player if it is still running
            }
            clip.setFramePosition(0); // rewind to the beginning
            clip.start();     // Start playing
        }
    }

    // Optional static method to pre-load all the sound files.
    static void init() {
        values(); // calls the constructor for all the elements
    }
}

SoundEffectDemo.java

import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
// Testing the SoundEffect enum in a Swing application
public class SoundEffectDemo extends JFrame {
    // Constructor
    public SoundEffectDemo() {
        // Pre-load all the sound files
        SoundEffect.init();
        SoundEffect.volume = SoundEffect.Volume.LOW;  // un-mute
        // Set up UI components
        Container cp = this.getContentPane();
        cp.setLayout(new FlowLayout(FlowLayout.CENTER, 10, 10));
        JButton btnSound1 = new JButton("Sound 1");
        btnSound1.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                SoundEffect.EXPLODE.play();
            }
        });
        cp.add(btnSound1);
        JButton btnSound2 = new JButton("Sound 2");
        btnSound2.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                SoundEffect.GONG.play();
            }
        });
        cp.add(btnSound2);
        JButton btnSound3 = new JButton("Sound 3");
        btnSound3.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                SoundEffect.SHOOT.play();
            }
        });
        cp.add(btnSound3);
        this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        this.setTitle("Test SoundEffct");
        this.pack();
        this.setVisible(true);
    }

    public static void main(String[] args) {
        new SoundEffectDemo();
    }
}

Screenshot :

Tidak ada komentar: