Create a gist now

Instantly share code, notes, and snippets.

What would you like to do?
import android.media.MediaRecorder;
import android.support.annotation.NonNull;
import com.f2prateek.rx.android.schedulers.AndroidSchedulers;
import java.io.File;
import java.io.IOException;
import java.util.concurrent.TimeUnit;
import rx.Observable;
import rx.subscriptions.Subscriptions;
public class RxMediaRecorder {
public static @NonNull MediaRecorder into(@NonNull File file) {
final MediaRecorder recorder = new MediaRecorder();
recorder.setAudioSource(MediaRecorder.AudioSource.MIC);
recorder.setOutputFormat(MediaRecorder.OutputFormat.AMR_WB);
recorder.setOutputFile(file.getAbsolutePath());
recorder.setAudioEncoder(MediaRecorder.AudioEncoder.AMR_WB);
return recorder;
}
public static @NonNull Observable<Long> record(@NonNull MediaRecorder recorder) {
return prepare(recorder).flatMap(RxMediaRecorder::stream);
}
static @NonNull Observable<MediaRecorder> prepare(@NonNull MediaRecorder recorder) {
return Observable.create(subscriber -> {
try {
Threads.assertBg();
recorder.prepare();
subscriber.onNext(recorder);
subscriber.onCompleted();
} catch (IOException e) {
subscriber.onError(e);
}
});
}
static @NonNull Observable<Long> stream(@NonNull MediaRecorder recorder) {
return Observable.create(sub -> {
sub.add(Subscriptions.create(() -> {
Threads.assertBg();
recorder.stop();
recorder.reset();
recorder.release();
}));
recorder.start();
final long start = System.currentTimeMillis();
sub.add(Observable.interval(16, TimeUnit.MILLISECONDS, AndroidSchedulers.mainThread())
.map(x -> System.currentTimeMillis() - start)
.subscribe(sub));
});
}
}

Brilliant!

uDevel commented Nov 23, 2016

Can you put license on this code so people can use it?

Thanks!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment