首頁  >  文章  >  Java  >  如何用Java播放WAV檔?

如何用Java播放WAV檔?

DDD
DDD原創
2024-11-14 20:38:02865瀏覽

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.

以上是如何用Java播放WAV檔?的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述:
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn