"If a worker wants to do his job well, he must first sharpen his tools." - Confucius, "The Analects of Confucius. Lu Linggong"
Front page > Programming > How to Play WAV Files in Java?

How to Play WAV Files in Java?

Published on 2024-11-19
Browse:484

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.

Latest tutorial More>

Disclaimer: All resources provided are partly from the Internet. If there is any infringement of your copyright or other rights and interests, please explain the detailed reasons and provide proof of copyright or rights and interests and then send it to the email: [email protected] We will handle it for you as soon as possible.

Copyright© 2022 湘ICP备2022001581号-3