Home  >  Article  >  Java  >  How to Play WAV Files in Java?

How to Play WAV Files in Java?

DDD
DDDOriginal
2024-11-14 20:38:02912browse

How to Play WAV Files in Java?

Playing WAV Files with Java

When developing Java applications, playing audio files is a common requirement. This tutorial provides a comprehensive solution for playing *.wav files, enabling you to incorporate sound effects and audio into your Java programs.

To begin, create a class to handle audio playback. In the example below, we create a MakeSound class that includes methods for playing audio files:

public class MakeSound {

    // Buffer size for reading audio data
    private final int BUFFER_SIZE = 128000;

    // Initialize audio variables
    private File soundFile;
    private AudioInputStream audioStream;
    private AudioFormat audioFormat;
    private SourceDataLine sourceLine;

    public void playSound(String filename) {
        // Open the audio file
        soundFile = new File(filename);
        audioStream = AudioSystem.getAudioInputStream(soundFile);
        
        // Get audio format
        audioFormat = audioStream.getFormat();
        
        // Open the audio output line
        DataLine.Info info = new DataLine.Info(SourceDataLine.class, audioFormat);
        sourceLine = (SourceDataLine) AudioSystem.getLine(info);
        sourceLine.open(audioFormat);
        
        // Start the audio line
        sourceLine.start();
        
        // Read and write the audio data
        int nBytesRead;
        byte[] abData = new byte[BUFFER_SIZE];
        while ((nBytesRead = audioStream.read(abData, 0, abData.length)) != -1) {
            sourceLine.write(abData, 0, nBytesRead);
        }
        
        // Stop and close the audio line
        sourceLine.drain();
        sourceLine.close();
    }
}

In your main application, you can use the MakeSound class to play audio files by calling the playSound() method, passing in the filename of the WAV file you want to play.

For instance, to play a short beep sound when a button is pressed, you can add the following code:

MakeSound sound = new MakeSound();
sound.playSound("beep.wav");

This solution provides a reliable and easy way to play *.wav files in Java applications, allowing you to add audio to your programs for enhanced functionality and user experience.

The above is the detailed content of How to Play WAV Files in Java?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn