Skip to content

Instantly share code, notes, and snippets.

@kotucz
Forked from meoyawn/RxMediaPlayer.java
Created December 14, 2015 16:37
Show Gist options
  • Save kotucz/3b861c61f64fd9891040 to your computer and use it in GitHub Desktop.
Save kotucz/3b861c61f64fd9891040 to your computer and use it in GitHub Desktop.
import android.media.AudioManager;
import android.media.MediaPlayer;
import android.util.Pair;
import org.jetbrains.annotations.NotNull;
import java.io.File;
import java.io.IOException;
import java.util.concurrent.TimeUnit;
import rx.Observable;
import rx.subscriptions.Subscriptions;
public class RxMediaPlayer {
public static @NotNull Observable<MediaPlayer> from(@NotNull File file) {
return Observable.create(subscriber -> {
final MediaPlayer player = create();
try {
player.setDataSource(file.getAbsolutePath());
subscriber.onNext(player);
subscriber.onCompleted();
} catch (IOException e) {
subscriber.onError(e);
}
});
}
public static @NotNull Observable<Pair<Integer, Integer>> play(@NotNull MediaPlayer mp) {
return prepare(mp).flatMap(RxMediaPlayer::stream);
}
static @NotNull MediaPlayer create() {
final MediaPlayer player = new MediaPlayer();
player.setAudioStreamType(AudioManager.STREAM_MUSIC);
return player;
}
static @NotNull Observable<MediaPlayer> prepare(@NotNull MediaPlayer mp) {
return Observable.create(subscriber -> {
try {
mp.prepare();
subscriber.onNext(mp);
subscriber.onCompleted();
} catch (IOException e) {
mp.reset();
mp.release();
subscriber.onError(e);
}
});
}
static @NotNull Observable<Pair<Integer, Integer>> stream(@NotNull MediaPlayer mp) {
return Observable.create(subscriber -> {
subscriber.add(Subscriptions.create(() -> {
if (mp.isPlaying()) {
mp.stop();
}
mp.reset();
mp.release();
}));
mp.start();
subscriber.add(ticks(mp)
.takeUntil(complete(mp))
.subscribe(subscriber));
});
}
static @NotNull Observable<Pair<Integer, Integer>> ticks(@NotNull MediaPlayer mp) {
return Observable.interval(16, TimeUnit.MILLISECONDS)
.map(y -> Pair.create(mp.getCurrentPosition(), mp.getDuration()));
}
static @NotNull Observable<MediaPlayer> complete(@NotNull MediaPlayer player) {
return Observable.create(subscriber -> player.setOnCompletionListener(mp -> {
subscriber.onNext(mp);
subscriber.onCompleted();
}));
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment