Created
May 25, 2015 17:41
-
-
Save ipcjs/3a80ca0f3b3df6bbe7bf to your computer and use it in GitHub Desktop.
监控麦克风音量~~
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package com.example.ipcjs.voicedemo; | |
import android.content.Context; | |
import android.media.MediaRecorder; | |
import android.os.Environment; | |
import android.os.Handler; | |
import java.io.File; | |
import java.io.IOException; | |
/** | |
* Created by ipcjs on 2015/5/26. | |
*/ | |
public class VolumeRecord { | |
private static final int MAX_AMPLITUDE = 32767; | |
private String mFilePath; | |
public interface VolumeCallback { | |
void onVolumeCallback(int progress); | |
} | |
private VolumeCallback mVolumeCallback; | |
private MediaRecorder mMediaRecorder; | |
private Context mContext; | |
public VolumeRecord(Context context, VolumeCallback volumeCallback) { | |
mContext = context; | |
mVolumeCallback = volumeCallback; | |
if (mContext.getExternalCacheDir() != null) { | |
mFilePath = mContext.getExternalCacheDir().getAbsolutePath(); | |
} else { | |
mFilePath = Environment.getExternalStorageState(); | |
} | |
mFilePath += "/" + getClass().getSimpleName() + ".3gp"; | |
} | |
public boolean isRecording() { | |
return mMediaRecorder != null; | |
} | |
public boolean start() { | |
if (isRecording()) { | |
return false; | |
} | |
mMediaRecorder = new MediaRecorder(); | |
mMediaRecorder.setAudioSource(MediaRecorder.AudioSource.MIC); | |
mMediaRecorder.setOutputFormat(MediaRecorder.OutputFormat.THREE_GPP); | |
mMediaRecorder.setAudioEncoder(MediaRecorder.AudioEncoder.AMR_NB); | |
mMediaRecorder.setOutputFile(mFilePath); | |
try { | |
mMediaRecorder.prepare(); | |
} catch (IOException e) { | |
e.printStackTrace(); | |
mMediaRecorder = null; | |
return false; | |
} | |
mMediaRecorder.start(); | |
updateUi(); | |
return true; | |
} | |
public void stop() { | |
if (isRecording()) { | |
mMediaRecorder.stop(); | |
mMediaRecorder.release(); | |
mMediaRecorder = null; | |
new File(mFilePath).delete(); | |
} | |
} | |
private void updateUi() { | |
if (!isRecording()) { | |
return; | |
} | |
int maxAmplitude = mMediaRecorder.getMaxAmplitude(); | |
if (mVolumeCallback != null) { | |
mVolumeCallback.onVolumeCallback((int) (100f * maxAmplitude / MAX_AMPLITUDE + 0.5)); | |
} | |
mHandler.postDelayed(mUpdateUiRunnable, 100); | |
} | |
private Runnable mUpdateUiRunnable = new Runnable() { | |
@Override | |
public void run() { | |
updateUi(); | |
} | |
}; | |
private Handler mHandler = new Handler(); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
权限: