使用Java播放WAV檔案
開發Java應用程式時,播放音訊檔案是一個常見的需求。本教學提供了播放 *.wav 檔案的全面解決方案,使您能夠將音效和音訊合併到 Java 程式中。
首先,建立一個類別來處理音訊播放。在下面的範例中,我們建立一個 MakeSound 類,其中包含播放音訊檔案的方法:
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(); } }
在主應用程式中,您可以使用 MakeSound 類別來播放音訊文件,方法是呼叫 playSound() 方法,傳入要播放的 WAV 檔案的檔案名稱。
For例如,要在按下按鈕時發出短暫的嘟嘟聲,可以添加以下程式碼:
MakeSound sound = new MakeSound(); sound.playSound("beep.wav");
此解決方案提供了一種在Java 應用程式中播放*.wav 檔案的可靠且簡單的方法,允許您向程式添加音訊以增強功能和使用者體驗。
免責聲明: 提供的所有資源部分來自互聯網,如果有侵犯您的版權或其他權益,請說明詳細緣由並提供版權或權益證明然後發到郵箱:[email protected] 我們會在第一時間內為您處理。
Copyright© 2022 湘ICP备2022001581号-3