MediaPlayer の状態とリソースを管理する
コレクションでコンテンツを整理
必要に応じて、コンテンツの保存と分類を行います。
このドキュメントでは、落とし穴になり得る 2 つの領域について説明します。
状態を管理する
MediaPlayer
は状態ベースです。つまり、操作によっては、プレーヤーが特定の状態のときにのみ有効になります。そのため、コードを記述する際には、常に の内部状態を意識する必要があります。状態に適さない操作を行うと、システムから例外がスローされるなど、望ましくない動作が発生する可能性があります。
MediaPlayer
クラスのドキュメントの状態遷移図では、MediaPlayer
の状態がどのメソッドによりどう変わるかがわかるようになっています。例:
図が示すように、この時点では、start()
、pause()
、seekTo()
などのメソッドを呼び出すことで、Started
、Paused
、PlaybackCompleted
の各状態間を行き来できます。
ただし、stop()
を呼び出した場合は、MediaPlayer
を再度準備するまで start()
を呼び出すことはできません。
状態に合わないメソッドの呼び出しは、よく見られるバグです。MediaPlayer
オブジェクトを操作するコードを記述する際は、常に状態遷移図を念頭に置いてください。
MediaPlayer を解放する
MediaPlayer
は、貴重なシステム リソースを消費する可能性があります。そのため、MediaPlayer
インスタンスが必要以上に長く存在することのないよう、常に特別な措置を講じなければなりません。使用を終了したら必ず release()
を呼び出して、割り当てられたシステム リソースが適切に解放されるようにする必要があります。
たとえば、MediaPlayer
を使用していて、アクティビティが onStop()
の呼び出しを受け取った場合、アクティビティがユーザーとやり取りしていない間に保持しておくのは意味がないため、MediaPlayer
を解放する必要があります(バックグラウンドでメディアを再生している場合を除きます。これは次のセクションで説明します)。
当然のことながら、アクティビティを再開または再起動するときには、再生を再開する前に、新しい MediaPlayer
を作成してもう一度準備を行う必要があります。
MediaPlayer
の解放と無効化は次のように行います。
Kotlin
mediaPlayer?.release()
mediaPlayer = null
Java
mediaPlayer.release();
mediaPlayer = null;
たとえば、アクティビティの停止時に MediaPlayer
を解放し忘れ、アクティビティの再起動時に新しく作成した場合に起こりうる問題を考えてみましょう。ユーザーが画面の向きを変更した場合(またはデバイスの構成を別の方法で変更した場合)、デフォルトではアクティビティが再起動されます。ユーザーがデバイスを縦向きと横向きを切り替えるたびに、新しい MediaPlayer
が作成され、解放されないため、システム リソースがすぐに消費される可能性があります。
ランタイムの再起動の詳細については、ランタイムの変更を処理するをご覧ください。
ユーザーがアクティビティを離れた場合でも、組み込みの音楽アプリで行うのと同様に、「バックグラウンド メディア」の再生を続けたい場合はどうすればよいか、という疑問が生じるかもしれません。この場合は、次のセクションで説明するように、サービスで制御する MediaPlayer
が必要になります。
詳細
アプリでのメディア再生には、Jetpack Media3 が推奨されるソリューションです。詳しくは、こちらをご覧ください。
以下は音声と動画の録音、録画、保存、再生に関するトピックを扱うページです。
このページのコンテンツやコードサンプルは、コンテンツ ライセンスに記載のライセンスに従います。Java および OpenJDK は Oracle および関連会社の商標または登録商標です。
最終更新日 2025-07-27 UTC。
[[["わかりやすい","easyToUnderstand","thumb-up"],["問題の解決に役立った","solvedMyProblem","thumb-up"],["その他","otherUp","thumb-up"]],[["必要な情報がない","missingTheInformationINeed","thumb-down"],["複雑すぎる / 手順が多すぎる","tooComplicatedTooManySteps","thumb-down"],["最新ではない","outOfDate","thumb-down"],["翻訳に関する問題","translationIssue","thumb-down"],["サンプル / コードに問題がある","samplesCodeIssue","thumb-down"],["その他","otherDown","thumb-down"]],["最終更新日 2025-07-27 UTC。"],[],[],null,["# Manage MediaPlayer state and resources\n\nThis document covers two areas with potential pitfalls.\n\n- **State.** With \"Medialayer\\`, certain operations are valid only in specific\n states. Incorrect operations can cause exceptions or unexpected behavior.\n\n- **Resources** When you make configuration changes, such as screen rotation,\n You must release a `MediaPlayer` object to free up system resources and\n avoid resource exhaustion.\n\nManage state\n------------\n\n[`MediaPlayer`](/reference/android/media/MediaPlayer) is state-based. That is, it has an\ninternal state that you must\nalways be aware of when you write your code, because certain operations are only\nvalid when the player is in specific states. If you perform an operation while\nin the wrong state, the system may throw an exception or cause other undesirable\nbehaviors.\n\nThe state diagram in the [`MediaPlayer`](/reference/android/media/MediaPlayer) class documentation clarifies\nwhich methods move the [`MediaPlayer`](/reference/android/media/MediaPlayer) from one state\nto another. For example:\n\n- When you create a new [`MediaPlayer`](/reference/android/media/MediaPlayer), it is in the *Idle* state.\n- You initialize it by calling[`setDataSource()`](/reference/android/media/MediaPlayer#setDataSource(android.content.Context,%20android.net.Uri)), which changes it to the *Initialized* state.\n- You prepare it using either the [`prepare()`](/reference/android/media/MediaPlayer#prepare()) or [`prepareAsync()`](/reference/android/media/MediaPlayer#prepareAsync()) method.\n- When the [`MediaPlayer`](/reference/android/media/MediaPlayer) is done preparing, it enters the `Prepared` state, which means you can call [`start()`](/reference/android/media/MediaPlayer#start()) to make it play the media.\n\nAt that point, as the diagram illustrates, you can move between the `Started`,\n`Paused` and `PlaybackCompleted` states by calling such methods as\n[`start()`](/reference/android/media/MediaPlayer#start()), [`pause()`](/reference/android/media/MediaPlayer#pause()), and [`seekTo()`](/reference/android/media/MediaPlayer#seekTo(int)), among others.\n\nWhen you call [`stop()`](/reference/android/media/MediaPlayer#stop()), however, notice that you cannot call [`start()`](/reference/android/media/MediaPlayer#start())\nagain until you prepare the [`MediaPlayer`](/reference/android/media/MediaPlayer) again.\n\nAlways keep [the state diagram](/static/images/mediaplayer_state_diagram.gif) in mind when writing code that interacts with\na [`MediaPlayer`](/reference/android/media/MediaPlayer) object, because calling its methods from the wrong state is\na common cause of bugs.\n\nRelease the MediaPlayer\n-----------------------\n\nA [`MediaPlayer`](/reference/android/media/MediaPlayer) can consume valuable system resources. Therefore, you\nshould always take extra precautions to make sure you are not hanging on to a\n[`MediaPlayer`](/reference/android/media/MediaPlayer) instance longer than necessary. When you are done with it,\nyou should always call [`release()`](/reference/android/media/MediaPlayer#release()) to make sure any system resources\nallocated to it are properly released.\n\nFor example, if you are using a [`MediaPlayer`](/reference/android/media/MediaPlayer) and your activity receives a\ncall to [`onStop()`](/reference/android/app/Activity#onStop()), you must release the [`MediaPlayer`](/reference/android/media/MediaPlayer), because it\nmakes little sense to hold on to it while your activity is not interacting with\nthe user (unless you are playing media in the background, which is discussed in\nthe next section).\n\nWhen your activity is resumed or restarted, of course, you need to create a new\n[`MediaPlayer`](/reference/android/media/MediaPlayer) and prepare it again before resuming playback.\n\nHere's how you should release and then nullify your [`MediaPlayer`](/reference/android/media/MediaPlayer): \n\n### Kotlin\n\n mediaPlayer?.release()\n mediaPlayer = null\n\n### Java\n\n mediaPlayer.release();\n mediaPlayer = null;\n\nAs an example, consider the problems that arise if you forget to release the\n[`MediaPlayer`](/reference/android/media/MediaPlayer) when your activity stops, but create a new one when the\nactivity starts again. When the user changes the screen orientation (or changes\nthe device configuration in another way), the system restarts the activity by\ndefault. You might quickly consume all of the system resources as the user\nrotates the device back and forth between portrait and landscape, because at\neach orientation change, you create a new [`MediaPlayer`](/reference/android/media/MediaPlayer) that you never\nrelease.\n\nFor more information about runtime restarts, see [Handling Runtime Changes](/guide/topics/resources/runtime-changes).\n\nYou may be wondering what happens if you want to continue playing \"background\nmedia\" even when the user leaves your activity, much in the same way that the\nbuilt-in Music application behaves. In this case, what you need is a\n[`MediaPlayer`](/reference/android/media/MediaPlayer) controlled by a Service, as discussed in the next section\n\nLearn more\n----------\n\nJetpack Media3 is the recommended solution for media playback in your app. [Read\nmore](/media/media3) about it.\n\nThese pages cover topics relating to recording, storing, and playing back audio\nand video:\n\n- [Supported Media Formats](/guide/topics/media/media-formats)\n- [MediaRecorder](/guide/topics/media/mediarecorder)\n- [Data Storage](/guide/topics/data/data-storage)"]]