Android pcm文件播放方法(AudioTrack)

pcm文件不能直接使用MediaPlayer进行播放,  因为mediaplayer不支持这种格式的音频文件, 

我们可以使用AudioTrack对录到的pcm文件进行播放, 使用AudioTrack的步骤如下:

1.获取一个合适的缓存区

int bufferSize = AudioTrack.getMinBufferSize(16000, AudioFormat.CHANNEL_OUT_MONO, AudioFormat.ENCODING_PCM_16BIT);

第一个参数是采样率这里我是用的是16000(另外还有8000等格式), 第二个参数是单声道还是多声道(这里我用的是单声道), 第三个表示录音数据的格式这里用的是PCM_16BIT

2.创建一个AudioTrack对象

 audioTrack = new AudioTrack(AudioManager.STREAM_MUSIC, 16000, AudioFormat.CHANNEL_OUT_MONO,AudioFormat.ENCODING_PCM_16BIT, bufferSize, AudioTrack.MODE_STREAM);

3.调用play()方法, 并向audiotrack里写入录音数据:

try {
	audioTrack.play();
	fis = new FileInputStream(path);
	byte[] buffer = new byte[bufferSize];
	int len = 0;
	isPlaying = true;
	while ((len = fis.read(buffer)) != -1 && !isStop) {
//                    Log.d(TAG, "playPCMRecord: len " + len);
		audioTrack.write(buffer, 0, len);
	}

} catch (Exception e) {
	Log.e(TAG, "playPCMRecord: e : " + e);
}

来看一个完整的写法:

private Runnable playPCMRecord = new Runnable() {
        @Override
        public void run() {
            int bufferSize = AudioTrack.getMinBufferSize(16000, AudioFormat.CHANNEL_OUT_MONO, AudioFormat.ENCODING_PCM_16BIT);
            audioTrack = new AudioTrack(AudioManager.STREAM_MUSIC, 16000, AudioFormat.CHANNEL_OUT_MONO,AudioFormat.ENCODING_PCM_16BIT, bufferSize, AudioTrack.MODE_STREAM);
            FileInputStream fis = null;
            try {
                audioTrack.play();
                fis = new FileInputStream(path);
                byte[] buffer = new byte[bufferSize];
                int len = 0;
                isPlaying = true;
                while ((len = fis.read(buffer)) != -1 && !isStop) {
//                    Log.d(TAG, "playPCMRecord: len " + len);
                    audioTrack.write(buffer, 0, len);
                }

            } catch (Exception e) {
                Log.e(TAG, "playPCMRecord: e : " + e);
            } finally {
                isPlaying = false;
                isStop = false;
                if (audioTrack != null) {
                    audioTrack.stop();
                    audioTrack = null;
                }
                if (fis != null) {
                    try {
                        fis.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
            }
        }
    };

 

你可能感兴趣的:(Android)