Created
August 10, 2014 01:24
-
-
Save anitasantoso/e05bd3dc347d982d6213 to your computer and use it in GitHub Desktop.
This file contains 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.isobar.operationlife.util; | |
import android.media.MediaRecorder; | |
import java.io.IOException; | |
import java.util.Timer; | |
import java.util.TimerTask; | |
/** | |
* Created by anitasantoso on 17/07/2014. | |
*/ | |
public class AudioRecorder { | |
public static interface AudioRecorderListener { | |
public void onTimeOut(); | |
public void onRecordDurationUpdated(long duration); | |
} | |
private static final int UPDATE_INTERVAL_IN_MILLIS = 1 * DateUtil.SEC_TO_MILLIS; | |
private static final long MAX_DURATION_IN_SECS = 3 * DateUtil.MIN_TO_SECS; | |
private AudioRecorderListener listener; | |
private Timer timer; | |
private long durationInSecs; // in seconds | |
private MediaRecorder recorder; | |
public AudioRecorder(AudioRecorderListener listener) { | |
assert(listener != null); | |
this.listener = listener; | |
} | |
/** | |
* Start audio recording for type | |
* | |
* @throws IOException if storage is unavailable | |
*/ | |
public void startRecording(String filename) throws IOException { | |
assert(filename != null); | |
// stop current recording if any | |
resetRecordingState(); | |
recorder = new MediaRecorder(); | |
recorder.setAudioSource(MediaRecorder.AudioSource.MIC); | |
recorder.setOutputFormat(MediaRecorder.OutputFormat.MPEG_4); | |
recorder.setAudioEncoder(MediaRecorder.AudioEncoder.DEFAULT); | |
recorder.setOutputFile(filename); | |
recorder.prepare(); | |
recorder.start(); | |
startTimer(); | |
} | |
public void resetRecordingState() { | |
if (timer != null) { | |
timer.cancel(); | |
timer.purge(); | |
} | |
if (recorder != null) { | |
recorder.stop(); | |
recorder.release(); | |
} | |
durationInSecs = 0; | |
} | |
private void startTimer() { | |
timer = new Timer(); | |
durationInSecs = 0; | |
// update every one second | |
timer.scheduleAtFixedRate(new TimerTask() { | |
@Override | |
public void run() { | |
durationInSecs++; | |
if (listener != null) { | |
listener.onRecordDurationUpdated(durationInSecs); | |
} | |
if (durationInSecs == MAX_DURATION_IN_SECS) { | |
if (listener != null) { | |
listener.onTimeOut(); | |
} | |
// stop timer | |
resetRecordingState(); | |
} | |
} | |
}, 0L, UPDATE_INTERVAL_IN_MILLIS); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment