Java-播放PCM文件

PCM文件是原始的采样音频文件,可以使用SourceDataLine进行播放,注意设置采样率(sampleRate)位数(sampleSizeInBits)以及单双声道(channels),有时还要注意下数据的大小端(bigEndian)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
public void playPCM(){
try {
File file = new File("/Users/YI/Desktop/audioMY.pcm");
System.out.println(file.length());
int offset = 0;
int bufferSize = Integer.valueOf(String.valueOf(file.length())) ;
byte[] audioData = new byte[bufferSize];
InputStream in = new FileInputStream(file);
in.read(audioData);

float sampleRate = 44100;
int sampleSizeInBits = 16;
int channels = 2;
boolean signed = true;
boolean bigEndian = false;
AudioFormat af = new AudioFormat(sampleRate, sampleSizeInBits, channels, signed, bigEndian);
SourceDataLine.Info info = new DataLine.Info(SourceDataLine.class, af, bufferSize);
SourceDataLine sdl = (SourceDataLine) AudioSystem.getLine(info);
sdl.open(af);
sdl.start();
sdl.addLineListener(new LineListener(){

@Override
public void update(LineEvent arg0) {
try {
if(currentIndex < ids.size())
queryMediaInfo(ids.get(currentIndex++));
} catch (Exception e) {
e.printStackTrace();
}
}

});
while (offset < audioData.length) {
offset += sdl.write(audioData, offset, bufferSize);
}
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}