To load and play a .wav
file using the AudioSystem
class in Java, you can use the Clip
interface from the javax.sound.sampled
package. The AudioSystem
class provides methods to get an audio input stream and obtain a clip to play the sound.
Here’s a step-by-step guide, including example code:
Steps:
- Import required packages from
javax.sound.sampled
. - Use
AudioSystem.getAudioInputStream()
to read the.wav
file into an audio stream. - Obtain a
Clip
object fromAudioSystem
. - Open the audio stream in the clip.
- Start playing the audio with the
start()
method.
Example Code
package org.kodejava.sound;
import javax.sound.sampled.*;
import java.io.File;
import java.io.IOException;
public class WavPlayer {
public static void main(String[] args) {
// Path to the .wav file
String filePath = "D:/Sound/sound.wav";
try {
// Load the audio file as a File object
File audioFile = new File(filePath);
// Get an AudioInputStream from the file
AudioInputStream audioStream = AudioSystem.getAudioInputStream(audioFile);
// Get a Clip object
Clip clip = AudioSystem.getClip();
// Open the audio stream in the clip
clip.open(audioStream);
// Start playing the audio
clip.start();
// Keep the program running to listen to the complete audio
System.out.println("Playing audio...");
Thread.sleep(clip.getMicrosecondLength() / 1000); // Convert microseconds to milliseconds
} catch (UnsupportedAudioFileException e) {
System.out.println("The specified audio file format is not supported.");
e.printStackTrace();
} catch (LineUnavailableException e) {
System.out.println("Audio line for playing the sound is unavailable.");
e.printStackTrace();
} catch (IOException e) {
System.out.println("Error occurred while trying to read the audio file.");
e.printStackTrace();
} catch (InterruptedException e) {
System.out.println("Playback was interrupted.");
e.printStackTrace();
}
}
}
How it Works:
AudioSystem.getAudioInputStream(File)
: Loads the audio file into an audio stream.AudioSystem.getClip()
: Obtains aClip
object for playback.clip.open(audioStream)
: Opens the audio stream in the clip.clip.start()
: Starts the playback.Thread.sleep()
: Ensures playback completes before the program exits.
Key Points to Consider:
- File Path: Replace
"D:/Sound/sound.wav"
with the correct path to your.wav
file. - Audio Format: Ensure the
.wav
file is in a supported format (e.g., linear PCM). - Thread Management: The thread is paused with
Thread.sleep()
to allow the entire audio clip to play before the program exits. Without this, the program could terminate before playback completes. - Exception Handling: Handle exceptions such as unsupported file formats or unavailable audio lines.