下面列出了android.media.AudioRecord#RECORDSTATE_STOPPED 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。
@Override
public void startPusher() {
if (null == audioRecord) {
return;
}
mPusherRuning = true;
if (audioRecord.getRecordingState() == AudioRecord.RECORDSTATE_STOPPED) {
try {
audioRecord.startRecording();
new Thread(new AudioRecordTask()).start();
} catch (Throwable th) {
th.printStackTrace();
if (null != mListener) {
mListener.onErrorPusher(-101);
}
}
}
}
/**
* NOTE: Should waiting all output buffer disappear queue input buffer
*/
private void feedAudioEncoder(int index) {
if (index < 0 || mForceStop.get()) return;
final AudioRecord r = Objects.requireNonNull(mMic, "maybe release");
final boolean eos = r.getRecordingState() == AudioRecord.RECORDSTATE_STOPPED;
final ByteBuffer frame = mEncoder.getInputBuffer(index);
int offset = frame.position();
int limit = frame.limit();
int read = 0;
if (!eos) {
read = r.read(frame, limit);
if (VERBOSE) Log.d(TAG, "Read frame data size " + read + " for index "
+ index + " buffer : " + offset + ", " + limit);
if (read < 0) {
read = 0;
}
}
long pstTs = calculateFrameTimestamp(read << 3);
int flags = BUFFER_FLAG_KEY_FRAME;
if (eos) {
flags = BUFFER_FLAG_END_OF_STREAM;
}
// feed frame to encoder
if (VERBOSE) Log.d(TAG, "Feed codec index=" + index + ", presentationTimeUs="
+ pstTs + ", flags=" + flags);
mEncoder.queueInputBuffer(index, offset, read, pstTs, flags);
}
public void startRecording() {
if (!isInitialized()) {
throw new IllegalArgumentException("AudioRecorder state is uninitialized.");
}
if (mAudioRecord.getRecordingState() != AudioRecord.RECORDSTATE_STOPPED) return;
mAudioRecord.startRecording();
}
@Override
public void release() {
if (null == audioRecord) {
return;
}
mPusherRuning = false;
if (audioRecord.getRecordingState() == AudioRecord.RECORDSTATE_STOPPED)
audioRecord.release();
audioRecord = null;
}
/**
* 判断是是否有录音权限
*/
public static boolean isHasAudioPermission(final Context context){
int bufferSizeInBytes = 0;
bufferSizeInBytes = AudioRecord.getMinBufferSize(44100,
AudioFormat.CHANNEL_IN_MONO, AudioFormat.ENCODING_PCM_16BIT);
AudioRecord audioRecord = new AudioRecord(MediaRecorder.AudioSource.MIC, 44100,
AudioFormat.CHANNEL_IN_MONO, AudioFormat.ENCODING_PCM_16BIT, bufferSizeInBytes);
//开始录制音频
//开始录制音频
try{
// 防止某些手机崩溃,例如联想
audioRecord.startRecording();
}catch (IllegalStateException e){
e.printStackTrace();
// AVLogUtils.e(TAG, Log.getStackTraceString(e));
}
/**
* 根据开始录音判断是否有录音权限
*/
if (audioRecord.getRecordingState() != AudioRecord.RECORDSTATE_RECORDING
&& audioRecord.getRecordingState() != AudioRecord.RECORDSTATE_STOPPED) {
// AVLogUtils.e(TAG, "audioRecord.getRecordingState() != AudioRecord.RECORDSTATE_RECORDING : " + audioRecord.getRecordingState());
return false;
}
if (audioRecord.getRecordingState() == AudioRecord.RECORDSTATE_STOPPED) {
//如果短时间内频繁检测,会造成audioRecord还未销毁完成,此时检测会返回RECORDSTATE_STOPPED状态,再去read,会读到0的size,可以更具自己的需求返回true或者false
return false;
}
byte[] bytes = new byte[1024];
int readSize = audioRecord.read(bytes, 0, 1024);
if (readSize == AudioRecord.ERROR_INVALID_OPERATION || readSize <= 0) {
// AVLogUtils.e(TAG, "readSize illegal : " + readSize);
return false;
}
audioRecord.stop();
audioRecord.release();
audioRecord = null;
return true;
}
@Override
public void run() {
try {
//初始化音频
int bufferSizeInBytes = AudioRecord
.getMinBufferSize(audioSampleRate, AudioFormat.CHANNEL_IN_MONO, AudioFormat.ENCODING_PCM_16BIT);
final AudioRecord
audioRecord = new AudioRecord(MediaRecorder.AudioSource.MIC, audioSampleRate, AudioFormat.CHANNEL_IN_MONO, AudioFormat.ENCODING_PCM_16BIT, bufferSizeInBytes);
if(audioRecord == null){
mOnAudioRecorderListener.onNotPermission();
return ;
}
audioRecord.startRecording();
/**
* 根据开始录音判断是否有录音权限
*/
if (audioRecord.getRecordingState() != AudioRecord.RECORDSTATE_RECORDING
&& audioRecord.getRecordingState() != AudioRecord.RECORDSTATE_STOPPED) {
// AVLogUtils.e(TAG, "audioRecord.getRecordingState() != AudioRecord.RECORDSTATE_RECORDING : " + audioRecord.getRecordingState());
isAudioPermission = false;
}
if (audioRecord.getRecordingState() == AudioRecord.RECORDSTATE_STOPPED) {
//如果短时间内频繁检测,会造成audioRecord还未销毁完成,此时检测会返回RECORDSTATE_STOPPED状态,再去read,会读到0的size,可以更具自己的需求返回true或者false
isAudioPermission = false;
}
if(!isAudioPermission){
mOnAudioRecorderListener.onNotPermission();
return ;
}
mOnAudioRecorderListener.onCanRecord(isAudioPermission);
byte[] data = new byte[2048];
while(isRecord){
if(audioRecord == null){
return ;
}
int offset = 0;
while(offset < 2048) {
int readSize = audioRecord.read(data, offset, data.length-offset);
offset+=readSize;
}
if(isAudioRecordWrite){//写入文件
HeyhouRecorder.getInstance().recordAudioNHW(data,audioSampleRate,HeyhouRecorder.FORMAT_S16,1024);
}
}
audioRecord.stop();
audioRecord.release();
}catch (Exception e) {
e.printStackTrace();
mOnAudioRecorderListener.onRecordError("录音失败");
}
}
public static void setRecordingStartFailed() {
recordingState = AudioRecord.RECORDSTATE_STOPPED;
}
@Override
public void run() {
recorder.startRecording();
if (recorder.getRecordingState() == AudioRecord.RECORDSTATE_STOPPED) {
recorder.stop();
IOException ioe = new IOException(
"Failed to start recording. Microphone might be already in use.");
mainHandler.post(new OnErrorEvent(ioe));
return;
}
Log.d(TAG, "Starting decoding");
decoder.startUtt();
short[] buffer = new short[bufferSize];
boolean inSpeech = decoder.getInSpeech();
// Skip the first buffer, usually zeroes
recorder.read(buffer, 0, buffer.length);
while (!interrupted()
&& ((timeoutSamples == NO_TIMEOUT) || (remainingSamples > 0))) {
int nread = recorder.read(buffer, 0, buffer.length);
if (-1 == nread) {
throw new RuntimeException("error reading audio buffer");
} else if (nread > 0) {
decoder.processRaw(buffer, nread, false, false);
// int max = 0;
// for (int i = 0; i < nread; i++) {
// max = Math.max(max, Math.abs(buffer[i]));
// }
// Log.e("!!!!!!!!", "Level: " + max);
if (decoder.getInSpeech() != inSpeech) {
inSpeech = decoder.getInSpeech();
mainHandler.post(new InSpeechChangeEvent(inSpeech));
}
if (inSpeech)
remainingSamples = timeoutSamples;
final Hypothesis hypothesis = decoder.hyp();
mainHandler.post(new ResultEvent(hypothesis, false));
}
if (timeoutSamples != NO_TIMEOUT) {
remainingSamples = remainingSamples - nread;
}
}
recorder.stop();
decoder.endUtt();
// Remove all pending notifications.
mainHandler.removeCallbacksAndMessages(null);
// If we met timeout signal that speech ended
if (timeoutSamples != NO_TIMEOUT && remainingSamples <= 0) {
mainHandler.post(new TimeoutEvent());
}
}
private void clean() {
//Cleaning threads and order matters.
//recordingExecService.shutdown();
scheduleExecService.shutdownNow();//shutdownNow() tries to kill the currently running tasks immediately
if(audioRecorder != null) {
audioRecorder.stop();
audioRecorder.release();
if(audioRecorder.getRecordingState() == AudioRecord.RECORDSTATE_STOPPED)
audioRecorder = null;
}
if(backgroundThread != null) {
Thread dummy = backgroundThread;
backgroundThread = null;
dummy.interrupt();
}
Log.i(TAG, "clean() released !");
}