Last active
April 24, 2018 12:08
-
-
Save meoyawn/d1a99de548ee9629513d 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
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)); | |
}); | |
} | |
} |
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
Brilliant!