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中文網其他相關文章!