Utiliser MediaPlayer et la gestion des droits numériques (DRM)
Restez organisé à l'aide des collections
Enregistrez et classez les contenus selon vos préférences.
À partir d'Android 8.0 (niveau d'API 26), MediaPlayer
inclut des API compatibles avec la lecture de contenus protégés par DRM. Les API DRM MediaPlayer sont semblables à l'API de bas niveau fournie par MediaDrm
, mais elles fonctionnent à un niveau supérieur et n'exposent pas les objets d'extraction, de DRM et de cryptographie sous-jacents.
Bien que l'API DRM MediaPlayer ne fournisse pas toutes les fonctionnalités de MediaDrm
, elle est compatible avec les cas d'utilisation les plus courants. L'implémentation actuelle peut gérer les types de contenu suivants:
- Fichiers multimédias locaux protégés par Widevine
- Fichiers multimédias en streaming ou à distance protégés par Widevine
L'extrait de code suivant montre comment utiliser les nouvelles méthodes DRM MediaPlayer
dans une implémentation synchrone.
Pour gérer les contenus multimédias contrôlés par DRM, vous devez inclure les nouvelles méthodes avec le flux habituel d'appels MediaPlayer, comme illustré dans cet exemple:
Kotlin
mediaPlayer?.apply {
setDataSource()
setOnDrmConfigHelper() // optional, for custom configuration
prepare()
drmInfo?.also {
prepareDrm()
getKeyRequest()
provideKeyResponse()
}
// MediaPlayer is now ready to use
start()
// ...play/pause/resume...
stop()
releaseDrm()
}
Java
setDataSource();
setOnDrmConfigHelper(); // optional, for custom configuration
prepare();
if (getDrmInfo() != null) {
prepareDrm();
getKeyRequest();
provideKeyResponse();
}
// MediaPlayer is now ready to use
start();
// ...play/pause/resume...
stop();
releaseDrm();
Commencez par initialiser l'objet MediaPlayer
et définir sa source à l'aide de setDataSource()
, comme d'habitude. Pour utiliser la protection DRM, procédez comme suit:
- Si vous souhaitez que votre application effectue une configuration personnalisée, définissez une interface
OnDrmConfigHelper
et associez-la au lecteur à l'aide de setOnDrmConfigHelper()
.
- Appelez
prepare()
.
- Appelez
getDrmInfo()
. Si la source contient du contenu DRM, la méthode renvoie une valeur MediaPlayer.DrmInfo
non nulle.
Si MediaPlayer.DrmInfo
existe:
- Examinez la carte des UUID disponibles et choisissez-en un.
- Préparez la configuration DRM pour la source actuelle en appelant
prepareDrm()
.
- Si vous avez créé et enregistré un rappel
OnDrmConfigHelper
, il est appelé pendant l'exécution de prepareDrm()
. Vous pouvez ainsi effectuer une configuration personnalisée des propriétés DRM avant d'ouvrir la session DRM. Le rappel est appelé de manière synchrone dans le thread qui a appelé prepareDrm()
. Pour accéder aux propriétés DRM, appelez getDrmPropertyString()
et setDrmPropertyString()
. Évitez d'effectuer des opérations longues.
- Si l'appareil n'a pas encore été provisionné,
prepareDrm()
accède également au serveur de provisionnement pour le provisionner. Cette opération peut prendre un certain temps, en fonction de la connectivité réseau.
- Pour obtenir un tableau d'octets de requête de clé opaque à envoyer à un serveur de licence, appelez
getKeyRequest()
.
- Pour informer le moteur DRM de la réponse de clé reçue du serveur de licences, appelez
provideKeyResponse()
. Le résultat dépend du type de requête de clé :
- Si la réponse concerne une requête de clé hors connexion, le résultat est un identifiant de jeu de clés. Vous pouvez utiliser cet identifiant de jeu de clés avec
restoreKeys()
pour restaurer les clés dans une nouvelle session.
- Si la réponse concerne une requête de streaming ou de publication, le résultat est nul.
Préparer la DRM de manière asynchrone
Par défaut, prepareDrm()
s'exécute de manière synchrone, ce qui bloque l'exécution jusqu'à la fin de la préparation. Toutefois, la toute première préparation DRM sur un nouvel appareil peut également nécessiter un provisionnement, géré en interne par prepareDrm()
, et peut prendre un certain temps en raison de l'opération réseau impliquée. Vous pouvez éviter le blocage sur prepareDrm()
en définissant et en définissant un MediaPlayer.OnDrmPreparedListener
.
Définissez un OnDrmPreparedListener
. prepareDrm()
effectue le provisionnement (si nécessaire) et la préparation en arrière-plan. Une fois le provisionnement et la préparation terminés, le système appelle l'écouteur. Ne faites aucune hypothèse sur la séquence d'appel ni sur le thread dans lequel l'écouteur s'exécute (sauf si vous enregistrez l'écouteur avec un thread de gestionnaire). Le système peut appeler l'écouteur avant ou après le retour de prepareDrm()
.
Configurer la DRM de manière asynchrone
Vous pouvez initialiser le DRM de manière asynchrone en créant et en enregistrant MediaPlayer.OnDrmInfoListener
pour la préparation du DRM et MediaPlayer.OnDrmPreparedListener
pour démarrer le lecteur. Ils fonctionnent avec prepareAsync()
, comme illustré dans cet exemple:
Kotlin
setOnPreparedListener()
setOnDrmInfoListener()
setDataSource()
prepareAsync()
// ...
// If the data source content is protected you receive a call to the onDrmInfo() callback.
override fun onDrmInfo(mediaPlayer: MediaPlayer, drmInfo: MediaPlayer.DrmInfo) {
mediaPlayer.apply {
prepareDrm()
getKeyRequest()
provideKeyResponse()
}
}
// When prepareAsync() finishes, you receive a call to the onPrepared() callback.
// If there is a DRM, onDrmInfo() sets it up before executing this callback,
// so you can start the player.
override fun onPrepared(mediaPlayer: MediaPlayer) {
mediaPlayer.start()
}
Java
setOnPreparedListener();
setOnDrmInfoListener();
setDataSource();
prepareAsync();
// ...
// If the data source content is protected you receive a call to the onDrmInfo() callback.
onDrmInfo() {
prepareDrm();
getKeyRequest();
provideKeyResponse();
}
// When prepareAsync() finishes, you receive a call to the onPrepared() callback.
// If there is a DRM, onDrmInfo() sets it up before executing this callback,
// so you can start the player.
onPrepared() {
start();
}
Gérer les éléments multimédias chiffrés
À partir d'Android 8.0 (niveau d'API 26), MediaPlayer
peut également déchiffrer le schéma de chiffrement commun (CENC) et les médias chiffrés au niveau de l'échantillon HLS (METHOD=SAMPLE-AES) pour les types de flux élémentaires H.264 et AAC. Les contenus multimédias chiffrés sur l'intégralité du segment (METHOD=AES-128) étaient auparavant compatibles.
En savoir plus
Jetpack Media3 est la solution recommandée pour la lecture multimédia dans votre application. En savoir plus
Ces pages traitent des sujets liés à l'enregistrement, au stockage et à la lecture d'audio et de vidéo:
Le contenu et les exemples de code de cette page sont soumis aux licences décrites dans la Licence de contenu. Java et OpenJDK sont des marques ou des marques déposées d'Oracle et/ou de ses sociétés affiliées.
Dernière mise à jour le 2025/07/27 (UTC).
[[["Facile à comprendre","easyToUnderstand","thumb-up"],["J'ai pu résoudre mon problème","solvedMyProblem","thumb-up"],["Autre","otherUp","thumb-up"]],[["Il n'y a pas l'information dont j'ai besoin","missingTheInformationINeed","thumb-down"],["Trop compliqué/Trop d'étapes","tooComplicatedTooManySteps","thumb-down"],["Obsolète","outOfDate","thumb-down"],["Problème de traduction","translationIssue","thumb-down"],["Mauvais exemple/Erreur de code","samplesCodeIssue","thumb-down"],["Autre","otherDown","thumb-down"]],["Dernière mise à jour le 2025/07/27 (UTC)."],[],[],null,["# Work with MediaPlayer and Digital Rights Management (DRM)\n\nStarting with Android 8.0 (API level 26), [`MediaPlayer`](/reference/android/media/MediaPlayer) includes APIs that\nsupport the playback of DRM-protected material. The MediaPlayer DRM APIs are\nsimilar to the low-level API provided by [`MediaDrm`](/reference/android/media/MediaDrm), but they operate at a\nhigher level and don't expose the underlying extractor, DRM, and crypto objects.\n\nAlthough the MediaPlayer DRM API does not provide the full functionality of\n[`MediaDrm`](/reference/android/media/MediaDrm), it supports the most common use cases. The current\nimplementation can handle the following content types:\n\n- Widevine-protected local media files\n- Widevine-protected remote or streaming media files\n\nThe following code snippet demonstrates how to use the new DRM `MediaPlayer`\nmethods in a synchronous implementation.\n\nTo manage DRM-controlled media, you need to include the new methods alongside\nthe usual flow of MediaPlayer calls, as shown in this example: \n\n### Kotlin\n\n mediaPlayer?.apply {\n setDataSource()\n setOnDrmConfigHelper() // optional, for custom configuration\n prepare()\n drmInfo?.also {\n prepareDrm()\n getKeyRequest()\n provideKeyResponse()\n }\n\n // MediaPlayer is now ready to use\n start()\n // ...play/pause/resume...\n stop()\n releaseDrm()\n }\n\n### Java\n\n setDataSource();\n setOnDrmConfigHelper(); // optional, for custom configuration\n prepare();\n if (getDrmInfo() != null) {\n prepareDrm();\n getKeyRequest();\n provideKeyResponse();\n }\n\n // MediaPlayer is now ready to use\n start();\n // ...play/pause/resume...\n stop();\n releaseDrm();\n\nStart by initializing the [`MediaPlayer`](/reference/android/media/MediaPlayer) object and setting its source using\n[`setDataSource()`](/reference/android/media/MediaPlayer#setDataSource(android.content.Context,%20android.net.Uri)), as usual. Then, to use DRM, perform these steps:\n\n1. If you want your app to perform custom configuration, define an [`OnDrmConfigHelper`](/reference/android/media/MediaPlayer.OnDrmConfigHelper) interface, and attach it to the player using [`setOnDrmConfigHelper()`](/reference/android/media/MediaPlayer#setOnDrmConfigHelper(android.media.MediaPlayer.OnDrmConfigHelper)).\n2. Call [`prepare()`](/reference/android/media/MediaPlayer#prepare()).\n3. Call [`getDrmInfo()`](/reference/android/media/MediaPlayer#getDrmInfo()). If the source has DRM content, the method returns a non-null [`MediaPlayer.DrmInfo`](/reference/android/media/MediaPlayer.DrmInfo) value.\n\nIf [`MediaPlayer.DrmInfo`](/reference/android/media/MediaPlayer.DrmInfo) exists:\n\n1. Examine the map of available UUIDs and choose one.\n2. Prepare the DRM configuration for the current source by calling [`prepareDrm()`](/reference/android/media/MediaPlayer#prepareDrm(java.util.UUID)).\n - If you created and registered an [`OnDrmConfigHelper`](/reference/android/media/MediaPlayer.OnDrmConfigHelper) callback, it is called while [`prepareDrm()`](/reference/android/media/MediaPlayer#prepareDrm(java.util.UUID)) is executing. This lets you perform custom configuration of the DRM properties before opening the DRM session. The callback is called synchronously in the thread that called [`prepareDrm()`](/reference/android/media/MediaPlayer#prepareDrm(java.util.UUID)). To access the DRM properties, call [`getDrmPropertyString()`](/reference/android/media/MediaPlayer#getDrmPropertyString(java.lang.String)) and [`setDrmPropertyString()`](/reference/android/media/MediaPlayer#setDrmPropertyString(java.lang.String,%20java.lang.String)). Avoid performing lengthy operations.\n - If the device has not yet been provisioned, [`prepareDrm()`](/reference/android/media/MediaPlayer#prepareDrm(java.util.UUID)) also accesses the provisioning server to provision the device. This can take a variable amount of time, depending on the network connectivity.\n3. To get an opaque key request byte array to send to a license server, call [`getKeyRequest()`](/reference/android/media/MediaPlayer#getKeyRequest(byte%5B%5D,%20byte%5B%5D,%20java.lang.String,%20int,%20java.util.Map%3Cjava.lang.String,%20java.lang.String%3E)).\n4. To inform the DRM engine about the key response received from the license server, call [`provideKeyResponse()`](/reference/android/media/MediaPlayer#provideKeyResponse(byte%5B%5D,%20byte%5B%5D)). The result depends on the type of key request:\n - If the response is for an offline key request, the result is a key-set identifier. You can use this key-set identifier with [`restoreKeys()`](/reference/android/media/MediaPlayer#restoreKeys(byte%5B%5D)) to restore the keys to a new session.\n - If the response is for a streaming or release request, the result is null.\n\nPrepare DRM asynchronously\n--------------------------\n\nBy default, [`prepareDrm()`](/reference/android/media/MediaPlayer#prepareDrm(java.util.UUID)) runs synchronously, blocking until preparation\nfinishes. However, the very first DRM preparation on a new device may also\nrequire provisioning, which [`prepareDrm()`](/reference/android/media/MediaPlayer#prepareDrm(java.util.UUID)) handles internally, and may take\nsome time to finish due to the network operation involved. You can avoid\nblocking on [`prepareDrm()`](/reference/android/media/MediaPlayer#prepareDrm(java.util.UUID)) by defining and setting a\n[`MediaPlayer.OnDrmPreparedListener`](/reference/android/media/MediaPlayer.OnDrmPreparedListener).\n\nSet an [`OnDrmPreparedListener`](/reference/android/media/MediaPlayer.OnDrmPreparedListener). [`prepareDrm()`](/reference/android/media/MediaPlayer#prepareDrm(java.util.UUID)) performs the\nprovisioning (if needed) and preparation in the background. When provisioning\nand preparation finish, the system calls the listener. Don't make any\nassumptions about the calling sequence or the thread in which the listener runs\n(unless you register the listener with a handler thread). The system can call\nthe listener before or after [`prepareDrm()`](/reference/android/media/MediaPlayer#prepareDrm(java.util.UUID)) returns.\n\nSet up DRM asynchronously\n-------------------------\n\nYou can initialize the DRM asynchronously by creating and registering the\n[`MediaPlayer.OnDrmInfoListener`](/reference/android/media/MediaPlayer.OnDrmInfoListener) for DRM preparation and the\n[`MediaPlayer.OnDrmPreparedListener`](/reference/android/media/MediaPlayer.OnDrmPreparedListener) to start the player. They work in\nconjunction with [`prepareAsync()`](/reference/android/media/MediaPlayer#prepareAsync()), as shown in this example: \n\n### Kotlin\n\n setOnPreparedListener()\n setOnDrmInfoListener()\n setDataSource()\n prepareAsync()\n // ...\n\n // If the data source content is protected you receive a call to the onDrmInfo() callback.\n override fun onDrmInfo(mediaPlayer: MediaPlayer, drmInfo: MediaPlayer.DrmInfo) {\n mediaPlayer.apply {\n prepareDrm()\n getKeyRequest()\n provideKeyResponse()\n }\n }\n\n // When prepareAsync() finishes, you receive a call to the onPrepared() callback.\n // If there is a DRM, onDrmInfo() sets it up before executing this callback,\n // so you can start the player.\n override fun onPrepared(mediaPlayer: MediaPlayer) {\n mediaPlayer.start()\n }\n\n### Java\n\n setOnPreparedListener();\n setOnDrmInfoListener();\n setDataSource();\n prepareAsync();\n // ...\n\n // If the data source content is protected you receive a call to the onDrmInfo() callback.\n onDrmInfo() {\n prepareDrm();\n getKeyRequest();\n provideKeyResponse();\n }\n\n // When prepareAsync() finishes, you receive a call to the onPrepared() callback.\n // If there is a DRM, onDrmInfo() sets it up before executing this callback,\n // so you can start the player.\n onPrepared() {\n\n start();\n }\n\nHandle encrypted media\n----------------------\n\nStarting with Android 8.0 (API level 26) `MediaPlayer` can also decrypt Common\nEncryption Scheme (CENC) and HLS sample-level encrypted media\n(METHOD=SAMPLE-AES) for the elementary stream types H.264, and AAC. Full-segment\nencrypted media (METHOD=AES-128) was previously supported.\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)"]]