在 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中文网其他相关文章!