Android录制和播放AudioRecord和AudioTrack

大兔子大兔子 提交于 2021-02-13 11:04:24
package com.esa.audio;

import android.media.AudioFormat;
import android.media.AudioManager;
import android.media.AudioRecord;
import android.media.AudioTrack;
import android.media.MediaRecorder;

public class Audio {

	public static final int AUDIO_SOURCE = MediaRecorder.AudioSource.MIC;
	public static final int STREAM_TYPE = AudioManager.STREAM_MUSIC;
	public static final int SAMPLE_RATE_IN_HZ = 8000;// 44100
	public static final int CHANNEL_CONFIG = AudioFormat.CHANNEL_CONFIGURATION_MONO;// AudioTrack和AudioRecord都能用
	public static final int RECORD_CHANNEL_CONFIG = AudioFormat.CHANNEL_IN_MONO;
	public static final int TRACK_CHANNEL_CONFIG = AudioFormat.CHANNEL_OUT_MONO;
	public static final int AUDIO_FORMAT = AudioFormat.ENCODING_PCM_16BIT;
	public static final int TRACK_BUFFER_SIZE_IN_BYTES = AudioTrack.getMinBufferSize(SAMPLE_RATE_IN_HZ, TRACK_CHANNEL_CONFIG, AUDIO_FORMAT);
	public static final int RECORD_BUFFER_SIZE_IN_BYTES = AudioRecord.getMinBufferSize(SAMPLE_RATE_IN_HZ, RECORD_CHANNEL_CONFIG, AUDIO_FORMAT);;
	public static final int MODE = AudioTrack.MODE_STREAM;

	private static Audio audio;
	private AudioTrack track = null;
	private AudioRecord record = null;

	public static Audio getAudio() {
		if (audio == null) {
			audio = new Audio();
		}
		return audio;
	}

	public AudioTrack getTrack() {
		if (track == null) {
			track = new AudioTrack(STREAM_TYPE, SAMPLE_RATE_IN_HZ, TRACK_CHANNEL_CONFIG, AUDIO_FORMAT, TRACK_BUFFER_SIZE_IN_BYTES, MODE);
		}
		return track;
	}

	public AudioRecord getRecord() {
		if (record == null) {
			record = new AudioRecord(AUDIO_SOURCE, SAMPLE_RATE_IN_HZ, RECORD_CHANNEL_CONFIG, AUDIO_FORMAT, RECORD_BUFFER_SIZE_IN_BYTES);
		}
		return record;
	}

	public void releaseRecord() {
		if (record != null) {
			record.stop();
			record.release();
		}
		record = null;
	}

	public void releaseTrack() {
		if (track != null) {
			track.stop();
			track.release();
		}
		track = null;
	}
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!