在 Java 中輕鬆播放 .WAV 檔案
使用正確的工具和技術,在 Java 中播放音訊檔案可以變得輕而易舉。讓我們透過在按下按鈕時播放簡單的蜂鳴聲來應對這項挑戰。
用於播放 .WAV 檔案的程式碼片段
要實現此目的,請使用下列 Java程式碼片段利用進階音訊功能:
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 PlaySound { private final int BUFFER_SIZE = 128000; private File soundFile; private AudioInputStream audioStream; private AudioFormat audioFormat; private SourceDataLine sourceLine; public void playSound(String filename){ String strFilename = filename; try { soundFile = new File(strFilename); } catch (Exception e) { e.printStackTrace(); System.exit(1); } try { audioStream = AudioSystem.getAudioInputStream(soundFile); } catch (Exception e){ e.printStackTrace(); System.exit(1); } audioFormat = audioStream.getFormat(); DataLine.Info info = new DataLine.Info(SourceDataLine.class, audioFormat); try { sourceLine = (SourceDataLine) AudioSystem.getLine(info); sourceLine.open(audioFormat); } catch (LineUnavailableException e) { e.printStackTrace(); System.exit(1); } catch (Exception e) { e.printStackTrace(); System.exit(1); } sourceLine.start(); int nBytesRead = 0; byte[] abData = new byte[BUFFER_SIZE]; while (nBytesRead != -1) { try { nBytesRead = audioStream.read(abData, 0, abData.length); } catch (IOException e) { e.printStackTrace(); } if (nBytesRead >= 0) { @SuppressWarnings("unused") int nBytesWritten = sourceLine.write(abData, 0, nBytesRead); } } sourceLine.drain(); sourceLine.close(); } }
逐步說明說明
以上是如何在Java中輕鬆播放.WAV檔?的詳細內容。更多資訊請關注PHP中文網其他相關文章!