如何使用java播放.wav文件我正在嘗試使用Java播放一個*.wav文件。我希望它能做到以下幾點(diǎn):當(dāng)按下按鈕時,播放一個簡短的嗶聲。我已經(jīng)在谷歌上搜索過了,但是大部分代碼都不起作用。有人能給我一個簡單的代碼片段來播放.wav文件嗎?
3 回答

森欄
TA貢獻(xiàn)1810條經(jīng)驗(yàn) 獲得超5個贊
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 MakeSound { private final int BUFFER_SIZE = 128000; private File soundFile; private AudioInputStream audioStream; private AudioFormat audioFormat; private SourceDataLine sourceLine; /** * @param filename the name of the file that is going to be played */ 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(); }}

絕地?zé)o雙
TA貢獻(xiàn)1946條經(jīng)驗(yàn) 獲得超4個贊
public static void play(String filename){ try { Clip clip = AudioSystem.getClip(); clip.open(AudioSystem.getAudioInputStream(new File(filename))); clip.start(); } catch (Exception exc) { exc.printStackTrace(System.out); }}
clip.drain()
start()
// ...clip.start();while (!clip.isRunning()) Thread.sleep(10);while (clip.isRunning()) Thread.sleep(10);clip.close();
添加回答
舉報
0/150
提交
取消