public enum PlayStatus {
NO_READY,
START,
STOP
}
private static final int AUDIO_SOURCE = MediaRecorder.AudioSource.MIC;
private static final int SAMPLE_RATE_INHZ = 44100;
private static final int CHANNEL_CONFIG = AudioFormat.CHANNEL_OUT_MONO;
private static final int AUDIO_FORMAT = AudioFormat.ENCODING_PCM_16BIT;
private final ExecutorService mExecutorService = Executors.newSingleThreadExecutor();
private AudioTrack mAudioTrack;
private PlayStatus mPlayStatus;
public void playPcmOnMainThread(String filePath) {
mExecutorService.execute(() -> {
try {
playPcm(filePath);
} catch (FileNotFoundException e) {
throw new RuntimeException(e);
}
});
}
//播放是文件流中读取所以需要放在子线程操作
@WorkerThread
public void playPcm(String filePath) throws FileNotFoundException {
int minBufferSizeInBytes = AudioTrack.getMinBufferSize(SAMPLE_RATE_INHZ, CHANNEL_CONFIG, AUDIO_FORMAT);
//注意在较新的Android设备中废弃了原本的构造方法
if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.M) {
AudioAttributes attributes = new AudioAttributes.Builder()
.setUsage(AudioAttributes.USAGE_MEDIA)
.setContentType(AudioAttributes.CONTENT_TYPE_MUSIC)
.setLegacyStreamType(AudioManager.STREAM_MUSIC)
.build();
AudioFormat audioFormat = new AudioFormat.Builder()
.setSampleRate(SAMPLE_RATE_INHZ)
.setChannelIndexMask(CHANNEL_CONFIG)
.setEncoding(AUDIO_FORMAT)
.build();
mAudioTrack = new AudioTrack.Builder()
.setAudioAttributes(attributes)
.setAudioFormat(audioFormat)
.setBufferSizeInBytes(minBufferSizeInBytes)
.setTransferMode(AudioTrack.MODE_STREAM)
.build();
} else {
mAudioTrack = new AudioTrack(
AudioManager.STREAM_MUSIC,
SAMPLE_RATE_INHZ,
CHANNEL_CONFIG,
AUDIO_FORMAT,
minBufferSizeInBytes,
AudioTrack.MODE_STREAM);
}
if (mAudioTrack == null) {
Log.e(TAG, "playPcm: create audiotrack error");
throw new IllegalArgumentException("playPcm: create audiotrack error");
}
File pcmFile = new File(filePath);
if (!pcmFile.exists()) {
throw new FileNotFoundException("pcmFile not found");
}
try (FileInputStream fis = new FileInputStream(pcmFile)) {
if (mPlayStatus != PlayStatus.START
&& mAudioTrack.getState() != AudioTrack.STATE_UNINITIALIZED
&& mAudioTrack.getState() != AudioTrack.PLAYSTATE_PLAYING) {
mPlayStatus = PlayStatus.START;
mAudioTrack.play();
}
byte[] bytes = new byte[minBufferSizeInBytes];
int dataLength = 0;
while ((dataLength = fis.read(bytes)) != -1 && mPlayStatus == PlayStatus.START) {
mAudioTrack.write(bytes, 0, dataLength);
}
} catch (IOException e) {
throw new RuntimeException(e);
}
}
从零开始的Android音视频学习(三)AudioTrack播放PCM音频
原创
©著作权归作者所有:来自51CTO博客作者wx5b5d3dddab5e1的原创作品,请联系作者获取转载授权,否则将追究法律责任
提问和评论都可以,用心的回复会被更多人看到
评论
发布评论
相关文章
-
详解音视频转码工具ffmpeg
详解ffmpeg
ide 封装 音视频 -
从零开始的Android音视频学习(一)三种方式绘制图片背景颜色 缩放 3c 音视频
-
从零开始学习音视频编程技术(四) FFMPEG的使用
.
FFMPEG SDL qt 视频 #include -
【音视频连载-007】基础学习篇-SDL 播放 PCM 音频文件(上)
SDL 播放音频系列~~
ios 音视频 采样率