・MediaPlayerクラスでの再生終了時にはMediaPlayer.release()を忘れずに
・再生が無事完了したあとが抜けがちなので要注意!
本論
ボタンを押したら音楽を再生、みたいなアプリを作っていたときに、ボタンを何度も押す(=何度も再生させる)と、ある時点から音楽再生が行われない問題に遭遇。その時には以下のようなエラーがlogcatに表示されていました。
12-27 18:17:19.712 5912-5924/com.example.mediaplayerstudy E/MediaPlayer: error (1, -19)
12-27 18:17:19.712 5912-5912/com.example.mediaplayerstudy E/MediaPlayer: Error (1,-19)
12-27 18:17:19.712 5912-5912/com.example.mediaplayerstudy E/MediaPlayer: Error (1,-19)
ググってみたら以下の書き込みに到達。
android - Mediaplayer error (-19,0) after repeated plays - Stack Overflow
http://stackoverflow.com/questions/9888510/mediaplayer-error-19-0-after-repeated-plays
なるほど、終了時にrelease()が必須だそうです。
しかし再生停止用のメソッドには、
public void stop() {
player.stop();
player.reset();
player.release();
}
って書いてるので問題ないはず…と思ってたのですが、これって明示的に停止したときにしか呼ばれないので、ちゃんと再生しきった時には何の後処理もしていない状況でした。
再生完了時にもきちんとrelease()するために、MediaPlayer.OnCompletionListener()を利用します。
player.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
@Override
public void onCompletion(MediaPlayer mediaPlayer) {
mediaPlayer.release();
}
});
onCompletionの引数にMediaPlayer自体が渡される理由ってこういう使い道だったのか…。
最初は以下の問題を踏んでしまったのかと思ったのですが、LollipopでもNougatでも起きてるのでどうやら違ったようです。
Issue 189051 - android - Marshmallow on NExus 5. A couple of serious problems. Bluetooth and wifi can't coexist, wifi always loses. Also, there is no notification sound when a text comes in when phone is locked. - Android Open Source Project - Issue Tracker - Google Project Hosting
https://code.google.com/p/android/issues/detail?id=189051
実証に使ったプロジェクトはそのうち公開するかもしないかも。