java播放wav音频文件

1.import相关包

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;
import javax.sound.sampled.UnsupportedAudioFileException;

2.加入如下代码

AudioInputStream as;
try {
	as = AudioSystem.getAudioInputStream(new File("img/1.wav"));//音频文件在项目根目录的img文件夹下
	AudioFormat format = as.getFormat();
	SourceDataLine sdl = null;
	DataLine.Info info = new DataLine.Info(SourceDataLine.class, format);
	sdl = (SourceDataLine) AudioSystem.getLine(info);
	sdl.open(format);
	sdl.start();
	int nBytesRead = 0;
	byte[] abData = new byte[512];
	while (nBytesRead != -1) {
		nBytesRead = as.read(abData, 0, abData.length);
		if (nBytesRead >= 0)
			sdl.write(abData, 0, nBytesRead);
	}
    //关闭SourceDataLine
	sdl.drain();
	sdl.close();
	}catch (UnsupportedAudioFileException | IOException | LineUnavailableException e) {
		// TODO Auto-generated catch block
		e.printStackTrace();
	}

可以单独起一个线程,用于播放声音,不然会等到声音放完程序才会继续往下走。

posted @ 2019-01-30 00:47  躲在车里的猫  阅读(1191)  评论(0)    收藏  举报