Android-使用AndroidTrack播放PCM音频

Android中,利用AndroidTrack可以直接播放PCM音频。

代码如下:

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
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
package com.baidu.carlife;
import android.media.AudioFormat;
import android.media.AudioManager;
import android.media.AudioTrack;
public class MyAudioTrack {
int mFrequency;// 采样率
int mChannel;// 声道
int mSampBit;// 采样精度
AudioTrack mAudioTrack;
public MyAudioTrack(int frequency, int channel, int sampbit){
mFrequency = frequency;
mChannel = channel;
mSampBit = sampbit;
}
public void init(){
if (mAudioTrack != null){
release();
}
if (mSampBit == 8)
mSampBit = AudioFormat.ENCODING_PCM_8BIT;
else
mSampBit = AudioFormat.ENCODING_PCM_16BIT;
if (mChannel == 1)
mChannel = AudioFormat.CHANNEL_IN_MONO;
else
mChannel = AudioFormat.CHANNEL_IN_STEREO;
int minBufSize = AudioTrack.getMinBufferSize(mFrequency, mChannel, mSampBit);
mAudioTrack = new AudioTrack(AudioManager.STREAM_MUSIC, mFrequency, mChannel, mSampBit, minBufSize, AudioTrack.MODE_STREAM);
mAudioTrack.play();
}
public void release(){
if (mAudioTrack != null){
mAudioTrack.stop();
mAudioTrack.release();
}
}
public void playAudioTrack(byte []data, int offset, int length){
if (data == null || data.length == 0){return ;}
try {
mAudioTrack.write(data, offset, length);
} catch (Exception e) {
e.printStackTrace();
}
}
public int getPrimePlaySize(){
int minBufSize = AudioTrack.getMinBufferSize(mFrequency, mChannel, mSampBit);
return minBufSize * 2;
}
}

调用的时候,只需要:

1
2
3
4
MyAudioTrack audioTrack = new MyAudioTrack(rate, channel, bit);
audioTrack.init();
byte[] resultData = new byte[length];
audioTrack.playAudioTrack(resultData, 0, resultData.length);
YI wechat
欢迎您扫一扫上面的微信公众号,订阅我的博客!