透過點擊按鈕使用Java 播放.WAV 檔案
開發Java 應用程式時,通常需要將音效或音訊播放合併到其中使用者體驗。本文示範如何在點擊按鈕時播放短促的 .wav 蜂鳴聲。
播放.WAV 檔案的程式碼片段
以下程式碼片段提供了詳細的解決方案問題:
import java.io.File; import java.io.IOException; import javax.sound.sampled.AudioFormat; import javax.sound.sampled.AudioInputStream; import javax.sound.sampled.AudioSystem; import javax.sound.sampled.DataLine; import javax.sound.sampled.LineUnavailableException; import javax.sound.sampled.SourceDataLine; public class PlayWAVFileOnClick { private static final int BUFFER_SIZE = 128000; private File soundFile; private AudioInputStream audioStream; private AudioFormat audioFormat; private SourceDataLine sourceLine; public static void main(String[] args) { // Instantiate a new PlayWAVFileOnClick object PlayWAVFileOnClick player = new PlayWAVFileOnClick(); // Specify the path to the .wav file String soundFilepath = "path/to/beep.wav"; // Play the sound player.playSound(soundFilepath); // Close resources after playback player.closeResources(); } public void playSound(String filename) { try { soundFile = new File(filename); audioStream = AudioSystem.getAudioInputStream(soundFile); audioFormat = audioStream.getFormat(); DataLine.Info info = new DataLine.Info(SourceDataLine.class, audioFormat); sourceLine = (SourceDataLine) AudioSystem.getLine(info); sourceLine.open(audioFormat); sourceLine.start(); byte[] data = new byte[BUFFER_SIZE]; int readSize = 0; while ((readSize = audioStream.read(data)) != -1) { sourceLine.write(data, 0, readSize); } } catch (IOException | LineUnavailableException e) { e.printStackTrace(); } } public void closeResources() { try { sourceLine.drain(); sourceLine.close(); audioStream.close(); } catch (IOException e) { e.printStackTrace(); } } }
說明
結論
使用此程式碼,Java 開發人員可以輕鬆地將.wav 聲音播放合併到他們的應用程式中,從而使他們能夠通過音效和通知來增強使用者體驗。
以上是如何在 Java 應用程式中點擊按鈕來播放 .WAV 檔案?的詳細內容。更多資訊請關注PHP中文網其他相關文章!