您的位置:首页 > 移动开发 > Android开发

[java] java pcm and android pcm. PCM声音

2015-12-14 00:05 656 查看

1, java 读取pcm

try {
File file = new File("C:\\Users\\cc\\Desktop\\reverseme.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);

System.out.println("read:" + bufferSize);
//javax.sound.sampled.AudioFormat
// sampleRate - 每秒的样本数 22050 44100
// sampleSizeInBits - 每个样本中的位数 16 ,8
// channels - 声道数(单声道 1 个,立体声 2 个)
// signed - 指示数据是有符号的,还是无符号的
// bigEndian - 指示是否以  字节顺序存 (大小端) 16位Bit就要看发送端的大小端模式.
//	              指示true是以 big-endian 顺序还是以 little-endian 顺序存储音频数据。
AudioFormat af = new AudioFormat(44100, 16, 2, true, false);
System.out.println(af.toString());
SourceDataLine.Info info = new DataLine.Info(SourceDataLine.class,
af, bufferSize);
SourceDataLine sdl = (SourceDataLine) AudioSystem.getLine(info);
sdl.open(af);
sdl.start();

while (offset < audioData.length) {
// offset += sdl.write(audioData, offset, bufferSize);
}
sdl.drain();
sdl.stop();
} catch (LineUnavailableException e) {
e.printStackTrace();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}

2,android

int bufferSize = AudioRecord.getMinBufferSize(44100,
AudioFormat.CHANNEL_IN_STEREO,
AudioFormat.ENCODING_PCM_16BIT);
AudioRecord audioRecord = new AudioRecord(
MediaRecorder.AudioSource.MIC, 44100,
AudioFormat.CHANNEL_IN_STEREO,
AudioFormat.ENCODING_PCM_16BIT, bufferSize);

byte[] buffer = new byte[bufferSize];
audioRecord.startRecording();

isRecording = true;
while (isRecording) {
int bufferReadResult = audioRecord.read(buffer, 0,
bufferSize);
OutBuff(buffer, bufferReadResult);
}
audioRecord.stop();


3. android播放
AudioTrack audioTrack = new AudioTrack(
AudioManager.STREAM_MUSIC, 44100,
AudioFormat.CHANNEL_OUT_STEREO,
AudioFormat.ENCODING_PCM_16BIT, musicLength * 2,
AudioTrack.MODE_STREAM);
// Start playback
audioTrack.play();

// Write the music buffer to the AudioTrack object
audioTrack.write(music, 0, musicLength);

audioTrack.stop();
附加说明:
声音处理须要的:

采样频率8000,44100(HZ), 位数16Bit,8Bit, 声道: 1,2
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: