The Android multimedia framework contains assist for enjoying number of widespread media sorts, so
that you may simply combine audio, video and pictures into your purposes. You may play audio or
video from media recordsdata saved in your utility’s assets (uncooked assets), from standalone recordsdata
within the filesystem, or from a knowledge stream arriving over a community connection, all utilizing MediaPlayer APIs.

This doc reveals you how one can use
MediaPlayer to write down a media-playing
utility that interacts with the consumer and the system to be able to receive good efficiency and a
nice consumer expertise. Alternatively, you would possibly need
to make use of ExoPlayer, which is a customizable open supply
library that helps high-performance options not accessible in MediaPlayer

Notice: You may play again the audio knowledge solely to the usual output
system. At present, that’s the cell system speaker or a Bluetooth headset. You can’t play sound
recordsdata within the dialog audio throughout a name.

The fundamentals

The next courses are used to play sound and video within the Android framework:

MediaPlayer
This class is the first API for enjoying sound and video.
AudioManager
This class manages audio sources and audio output on a tool.

Manifest declarations

Earlier than beginning improvement in your utility utilizing MediaPlayer, make sure that your manifest has
the suitable declarations to permit use of associated options.

  • Web Permission – In case you are utilizing MediaPlayer to stream network-based
    content material, your utility should request community entry.

    <uses-permission android_name="android.permission.INTERNET" />
    
  • Wake Lock Permission – In case your participant utility must preserve the display
    from dimming or the processor from sleeping, or makes use of the MediaPlayer.setScreenOnWhilePlaying() or
    MediaPlayer.setWakeMode() strategies, you should request this permission.

    <uses-permission android_name="android.permission.WAKE_LOCK" />
    

Utilizing MediaPlayer

Some of the vital elements of the media framework is the
MediaPlayer
class. An object of this class can fetch, decode, and play each audio and video
with minimal setup. It helps a number of completely different media sources resembling:

  • Native assets
  • Inside URIs, resembling one you would possibly receive from a Content material Resolver
  • Exterior URLs (streaming)

For an inventory of media codecs that Android helps,
see the Supported Media
Codecs
web page.

Right here is an instance
of how one can play audio that is accessible as a neighborhood uncooked useful resource (saved in your utility’s
res/uncooked/ listing):

Kotlin

var mediaPlayer = MediaPlayer.create(context, R.uncooked.sound_file_1)
mediaPlayer.begin() // no must name put together(); create() does that for you

Java

MediaPlayer mediaPlayer = MediaPlayer.create(context, R.uncooked.sound_file_1);
mediaPlayer.begin(); // no must name put together(); create() does that for you

On this case, a “raw” useful resource is a file that the system doesn’t
attempt to parse in any explicit means. Nonetheless, the content material of this useful resource shouldn’t
be uncooked audio. It must be a correctly encoded and formatted media file in a single
of the supported codecs.

And right here is the way you would possibly play from a URI accessible domestically within the system
(that you simply obtained via a Content material Resolver, for example):

Kotlin

val myUri: Uri = .... // initialize Uri right here
val mediaPlayer = MediaPlayer().apply {
    setAudioAttributes(
        AudioAttributes.Builder()
            .setContentType(AudioAttributes.CONTENT_TYPE_MUSIC)
            .setUsage(AudioAttributes.USAGE_MEDIA)
            .construct()
    )
    setDataSource(applicationContext, myUri)
    put together()
    begin()
}

Java

Uri myUri = ....; // initialize Uri right here
MediaPlayer mediaPlayer = new MediaPlayer();
mediaPlayer.setAudioAttributes(
    new AudioAttributes.Builder()
        .setContentType(AudioAttributes.CONTENT_TYPE_MUSIC)
        .setUsage(AudioAttributes.USAGE_MEDIA)
        .construct()
);
mediaPlayer.setDataSource(getApplicationContext(), myUri);
mediaPlayer.put together();
mediaPlayer.begin();

Taking part in from a distant URL through HTTP streaming seems like this:

Kotlin

val url = "http://........" // your URL right here
val mediaPlayer = MediaPlayer().apply {
    setAudioAttributes(
        AudioAttributes.Builder()
            .setContentType(AudioAttributes.CONTENT_TYPE_MUSIC)
            .setUsage(AudioAttributes.USAGE_MEDIA)
            .construct()
    )
    setDataSource(url)
    put together() // would possibly take lengthy! (for buffering, and many others)
    begin()
}

Java

String url = "http://........"; // your URL right here
MediaPlayer mediaPlayer = new MediaPlayer();
mediaPlayer.setAudioAttributes(
    new AudioAttributes.Builder()
        .setContentType(AudioAttributes.CONTENT_TYPE_MUSIC)
        .setUsage(AudioAttributes.USAGE_MEDIA)
        .construct()
);
mediaPlayer.setDataSource(url);
mediaPlayer.put together(); // would possibly take lengthy! (for buffering, and many others)
mediaPlayer.begin();

Notice:
In case you’re passing a URL to stream a web based media file, the file have to be able to
progressive obtain.

Warning: It’s essential to both catch or move
IllegalArgumentException and IOException when utilizing
setDataSource(), as a result of
the file you might be referencing won’t exist.

Asynchronous preparation

Utilizing MediaPlayer might be easy in
precept. Nonetheless, it is vital to needless to say a couple of extra issues are
essential to combine it accurately with a typical Android utility. For
instance, the decision to put together() can
take a very long time to execute, as a result of
it would contain fetching and decoding media knowledge. So, as is the case with any
technique which will take lengthy to execute, you need to by no means name it out of your
utility’s UI thread
. Doing that causes the UI to hold till the tactic returns,
which is a really dangerous consumer expertise and might trigger an ANR (Software Not Responding) error. Even when
you anticipate your useful resource to load rapidly, do not forget that something that takes greater than a tenth
of a second to reply within the UI causes a noticeable pause and provides
the consumer the impression that your utility is gradual.

To keep away from hanging your UI thread, spawn one other thread to
put together the MediaPlayer and notify the primary thread when carried out. Nonetheless, whereas
you can write the threading logic
your self, this sample is so widespread when utilizing MediaPlayer that the framework
provides a handy solution to accomplish this process by utilizing the
prepareAsync() technique. This technique
begins making ready the media within the background and returns instantly. When the media
is completed making ready, the onPrepared()
technique of the MediaPlayer.OnPreparedListener, configured via
setOnPreparedListener() is known as.

Managing state

One other facet of a MediaPlayer that you need to consider is
that it is state-based. That’s, the MediaPlayer has an inside state
that you should at all times pay attention to when writing your code, as a result of sure operations
are solely legitimate when the participant is in particular states. In case you carry out an operation whereas within the
incorrect state, the system could throw an exception or trigger different undesirable behaviors.

See also  George Houston

The documentation within the
MediaPlayer class reveals a whole state diagram,
that clarifies which strategies transfer the MediaPlayer from one state to a different.
For instance, whenever you create a brand new MediaPlayer, it’s within the Idle
state. At that time, you need to initialize it by calling
setDataSource(), bringing it
to the Initialized state. After that, it’s a must to put together it utilizing both the
put together() or
prepareAsync() technique. When
the MediaPlayer is completed making ready, it enters the Ready
state, which suggests you may name begin()
to make it play the media. At that time, because the diagram illustrates,
you may transfer between the Began, Paused and PlaybackCompleted states by
calling such strategies as
begin(),
pause(), and
seekTo(),
amongst others. If you
name cease(), nevertheless, discover that you simply
can’t name begin() once more till you
put together the MediaPlayer once more.

At all times preserve the state diagram
in thoughts when writing code that interacts with a
MediaPlayer object, as a result of calling its strategies from the incorrect state is a
widespread explanation for bugs.

Releasing the MediaPlayer

A MediaPlayer can devour precious
system assets.
Due to this fact, you need to at all times take further precautions to ensure you will not be
hanging on to a MediaPlayer occasion longer than needed. If you
are carried out with it, you need to at all times name
launch() to ensure any
system assets allotted to it are correctly launched. For instance, if you’re
utilizing a MediaPlayer and your exercise receives a name to onStop(), you should launch the MediaPlayer,
as a result of it
makes little sense to carry on to it whereas your exercise is just not interacting with
the consumer (except you might be enjoying media within the background, which is mentioned within the subsequent part).
When your exercise is resumed or restarted, in fact, it’s good to
create a brand new MediaPlayer and put together it once more earlier than resuming playback.

Here is how you need to launch after which nullify your MediaPlayer:

Kotlin

mediaPlayer?.launch()
mediaPlayer = null

Java

mediaPlayer.launch();
mediaPlayer = null;

For example, think about the issues that might occur when you
forgot to launch the MediaPlayer when your exercise is stopped, however create a
new one when the exercise begins once more. As chances are you’ll know, when the consumer modifications the
display orientation (or modifications the system configuration in one other means),
the system handles that by restarting the exercise (by default), so that you would possibly rapidly
devour all the system assets because the consumer
rotates the system forwards and backwards between portrait and panorama, as a result of at every
orientation change, you create a brand new MediaPlayer that you simply by no means
launch. (For extra details about runtime restarts, see Dealing with Runtime Modifications.)

It’s possible you’ll be questioning what occurs if you wish to proceed enjoying
“background media” even when the consumer leaves your exercise, a lot in the identical
means that the built-in Music utility behaves. On this case, what you want is
a MediaPlayer managed by a Service, as
mentioned within the subsequent part

Utilizing MediaPlayer in a service

In order for you your media to play within the background even when your utility
is just not onscreen—that’s, you need it to proceed enjoying whereas the consumer is
interacting with different purposes—then you should begin a
Service and management the
MediaPlayer occasion from there.
It’s essential to embed the
MediaPlayer in a MediaBrowserServiceCompat service and have
it work together with a
MediaBrowserCompat in one other exercise.

Try to be cautious about this consumer/server setup. There are expectations
about how a participant working in a background service interacts with the remainder of the
system. In case your utility doesn’t fulfill these expectations, the consumer could
have a foul expertise. Learn
Constructing an Audio App
for the total particulars.

This part describes particular directions for managing a MediaPlayer when it’s carried out inside a service.

Operating asynchronously

To start with, like an Exercise, all work in a
Service is completed in a single thread by
default—in actual fact, when you’re working an exercise and a service from the identical utility, they
use the identical thread (the “main thread”) by default. Due to this fact, providers must
course of incoming intents rapidly
and by no means carry out prolonged computations when responding to them. If any heavy
work or blocking calls are anticipated, you should do these duties asynchronously: both from
one other thread you implement your self, or utilizing the framework’s many amenities
for asynchronous processing.

As an example, when utilizing a MediaPlayer out of your important thread,
you need to name prepareAsync() quite than
put together(), and implement
a MediaPlayer.OnPreparedListener
to be able to be notified when the preparation is full and you can begin enjoying.
For instance:

Kotlin

personal const val ACTION_PLAY: String = "com.example.action.PLAY"

class MyService: Service(), MediaPlayer.OnPreparedListener {

    personal var mMediaPlayer: MediaPlayer? = null

    override enjoyable onStartCommand(intent: Intent, flags: Int, startId: Int): Int {
        ...
        val motion: String = intent.motion
        when(motion) {
            ACTION_PLAY -> {
                mMediaPlayer = ... // initialize it right here
                mMediaPlayer?.apply {
                    setOnPreparedListener(this@MyService)
                    prepareAsync() // put together async to not block important thread
                }

            }
        }
        ...
    }

    /** Referred to as when MediaPlayer is prepared */
    override enjoyable onPrepared(mediaPlayer: MediaPlayer) {
        mediaPlayer.begin()
    }
}

Java

public class MyService extends Service implements MediaPlayer.OnPreparedListener {
    personal static remaining String ACTION_PLAY = "com.example.action.PLAY";
    MediaPlayer mediaPlayer = null;

    public int onStartCommand(Intent intent, int flags, int startId) {
        ...
        if (intent.getAction().equals(ACTION_PLAY)) {
            mediaPlayer = ... // initialize it right here
            mediaPlayer.setOnPreparedListener(this);
            mediaPlayer.prepareAsync(); // put together async to not block important thread
        }
    }

    /** Referred to as when MediaPlayer is prepared */
    public void onPrepared(MediaPlayer participant) {
        participant.begin();
    }
}

Dealing with asynchronous errors

On synchronous operations, errors would usually
be signaled with an exception or an error code, however everytime you use asynchronous
assets, you need to make sure that your utility is notified
of errors appropriately. Within the case of a MediaPlayer,
you may accomplish this by implementing a
MediaPlayer.OnErrorListener and
setting it in your MediaPlayer occasion:

See also  IntelliJ IDEA

Kotlin

class MyService : Service(), MediaPlayer.OnErrorListener {

    personal var mediaPlayer: MediaPlayer? = null

    enjoyable initMediaPlayer() {
        // ...initialize the MediaPlayer right here...
        mediaPlayer?.setOnErrorListener(this)
    }

    override enjoyable onError(mp: MediaPlayer, what: Int, further: Int): Boolean {
        // ... react appropriately ...
        // The MediaPlayer has moved to the Error state, have to be reset!
    }
}

Java

public class MyService extends Service implements MediaPlayer.OnErrorListener {
    MediaPlayer mediaPlayer;

    public void initMediaPlayer() {
        // ...initialize the MediaPlayer right here...
        mediaPlayer.setOnErrorListener(this);
    }

    @Override
    public boolean onError(MediaPlayer mp, int what, int further) {
        // ... react appropriately ...
        // The MediaPlayer has moved to the Error state, have to be reset!
    }
}

It is vital to do not forget that when an error happens, the MediaPlayer
strikes to the Error state (see the documentation for the
MediaPlayer class for the total state diagram)
and you should reset it earlier than you should utilize it once more.

Utilizing wake locks

When designing purposes that play media
within the background, the system could fall asleep
whereas your service is working. As a result of the Android system tries to preserve
battery whereas the system is sleeping, the system tries to close off any
of the telephone’s options which can be
not needed, together with the CPU and the WiFi {hardware}.
Nonetheless, in case your service is enjoying or streaming music, you wish to forestall
the system from interfering together with your playback.

To be able to make sure that your service continues to run beneath
these circumstances, it’s a must to use “wake locks.” A wake lock is a solution to sign to
the system that your utility is utilizing some characteristic that ought to
keep accessible even when the telephone is idle.

Discover: It is best to at all times use wake locks sparingly and maintain them
solely for so long as actually needed, as a result of they considerably cut back the battery lifetime of the
system.

To make sure that the CPU continues working whereas your MediaPlayer is
enjoying, name the setWakeMode() technique when initializing your MediaPlayer. When you do,
the MediaPlayer holds the desired lock whereas enjoying and releases the lock
when paused or stopped:

Kotlin

mediaPlayer = MediaPlayer().apply {
    // ... different initialization right here ...
    setWakeMode(applicationContext, PowerManager.PARTIAL_WAKE_LOCK)
}

Java

mediaPlayer = new MediaPlayer();
// ... different initialization right here ...
mediaPlayer.setWakeMode(getApplicationContext(), PowerManager.PARTIAL_WAKE_LOCK);

Nonetheless, the wake lock acquired on this instance ensures solely that the CPU stays awake. If
you might be streaming media over the
community and you might be utilizing Wi-Fi, you most likely wish to maintain a
WifiLock as
properly, which you should purchase and launch manually. So, whenever you begin making ready the
MediaPlayer with the distant URL, you need to create and purchase the Wi-Fi lock.
For instance:

Kotlin

val wifiManager = getSystemService(Context.WIFI_SERVICE) as WifiManager
val wifiLock: WifiManager.WifiLock =
    wifiManager.createWifiLock(WifiManager.WIFI_MODE_FULL, "mylock")

wifiLock.purchase()

Java

WifiLock wifiLock = ((WifiManager) getSystemService(Context.WIFI_SERVICE))
    .createWifiLock(WifiManager.WIFI_MODE_FULL, "mylock");

wifiLock.purchase();

If you pause or cease your media, or whenever you now not want the
community, you need to launch the lock:

Kotlin

wifiLock.launch()

Java

wifiLock.launch();

Performing cleanup

As talked about earlier, a MediaPlayer object can devour a major
quantity of system assets, so you need to preserve it solely for so long as you want and name
launch() when you’re carried out with it. It is vital
to name this cleanup technique explicitly quite than depend on system rubbish assortment as a result of
it would take a while earlier than the rubbish collector reclaims the MediaPlayer,
because it’s solely delicate to reminiscence wants and to not scarcity of different media-related assets.
So, within the case whenever you’re utilizing a service, you need to at all times override the
onDestroy() technique to ensure you are releasing
the MediaPlayer:

Kotlin

class MyService : Service() {

    personal var mediaPlayer: MediaPlayer? = null
    // ...

    override enjoyable onDestroy() {
        tremendous.onDestroy()
        mediaPlayer?.launch()
    }
}

Java

public class MyService extends Service {
   MediaPlayer mediaPlayer;
   // ...

   @Override
   public void onDestroy() {
       tremendous.onDestroy();
       if (mediaPlayer != null) mediaPlayer.launch();
   }
}

It is best to at all times search for different alternatives to launch your MediaPlayer
as properly, other than releasing it when being shut down. For instance, when you anticipate not
to have the ability to play media for an prolonged time period (after dropping audio focus, for instance),
you need to positively launch your present MediaPlayer and create it once more
later. On the
different hand, when you solely anticipate to cease playback for a really quick time, you need to most likely
maintain on to your MediaPlayer to keep away from the overhead of making and making ready it
once more.

Digital Rights Administration (DRM)

Beginning with Android 8.0 (API degree 26), MediaPlayer contains APIs that
assist the playback of DRM-protected materials. They’re much like the low-level API offered by
MediaDrm, however they function at a better degree and don’t
expose the underlying extractor, drm, and crypto objects.

Though the MediaPlayer DRM API doesn’t present the total performance of
MediaDrm, it helps the most typical use instances. The
present implementation can deal with the next content material sorts:

  • Widevine-protected native media recordsdata
  • Widevine-protected distant/streaming media recordsdata
See also  Top 6 CDA do aplikacji konwertera MP3, które powinieneś wiedzieć

The next code snippet demonstrates how one can use the brand new DRM MediaPlayer
strategies in a easy synchronous implementation.

To handle DRM-controlled media, it’s good to embrace the brand new strategies alongside
the standard circulation of MediaPlayer calls, as proven beneath:

Kotlin

mediaPlayer?.apply {
    setDataSource()
    setOnDrmConfigHelper() // non-obligatory, for customized configuration
    put together()
    drmInfo?.additionally {
        prepareDrm()
        getKeyRequest()
        provideKeyResponse()
    }

    // MediaPlayer is now prepared to make use of
    begin()
    // ...play/pause/resume...
    cease()
    releaseDrm()
}

Java

setDataSource();
setOnDrmConfigHelper(); // non-obligatory, for customized configuration
put together();
if (getDrmInfo() != null) {
  prepareDrm();
  getKeyRequest();
  provideKeyResponse();
}

// MediaPlayer is now prepared to make use of
begin();
// ...play/pause/resume...
cease();
releaseDrm();

Begin by initializing the MediaPlayer object and setting
its supply utilizing setDataSource(),
as normal. Then, to make use of DRM, carry out these steps:

  1. In order for you your app to carry out customized configuration, outline an
    OnDrmConfigHelper interface, and connect it to the
    participant utilizing
    setOnDrmConfigHelper().
  2. Name put together().
  3. Name getDrmInfo(). If the supply has DRM
    content material, the tactic returns a non-null
    MediaPlayer.DrmInfo worth.

If MediaPlayer.DrmInfo exists:

  1. Look at the map of obtainable UUIDs and select one.
  2. Put together the DRM configuration for the present supply by calling prepareDrm().
  • In case you created and registered an
    OnDrmConfigHelper callback, it’s referred to as
    whereas prepareDrm()
    is executing. This allows you to carry out customized configuration of the DRM
    properties earlier than opening the DRM session. The callback is known as
    synchronously within the thread that referred to as
    prepareDrm(). To
    entry the DRM properties, name
    getDrmPropertyString() and
    setDrmPropertyString().
    Keep away from performing prolonged operations.
  • If the system has not but been provisioned,
    prepareDrm() additionally
    accesses the provisioning server to provision the system. This could take a
    variable period of time, relying on the community connectivity.
  • To get an opaque key request byte array to ship to a license server, name
    getKeyRequest().
  • To tell the DRM engine about the important thing response acquired from the license server, name
    provideKeyResponse(). The outcome will depend on the kind of key request:

    • If the response is for an offline key request, the result’s a key-set identifier. You need to use
      this key-set identifier with restoreKeys() to revive the keys to a brand new
      session.
    • If the response is for a streaming or launch request, the result’s null.
  • Operating prepareDrm() asynchronously

    By default, prepareDrm()
    runs synchronously, blocking till preparation is completed. Nonetheless, the very
    first DRM preparation on a brand new system may additionally require provisioning, which is
    dealt with internally by
    prepareDrm(), and
    could take a while to complete because of the community operation concerned. You may
    keep away from blocking on
    prepareDrm() by
    defining and setting a MediaPlayer.OnDrmPreparedListener.

    If you set an OnDrmPreparedListener,
    prepareDrm()
    performs the provisioning (if wanted) and preparation within the background. When
    provisioning and preparation have completed, the listener is known as. It is best to
    not make any assumption in regards to the calling sequence or the thread through which the
    listener runs (except the listener is registered with a handler thread).
    The listener might be referred to as earlier than or after
    prepareDrm()
    returns.

    Organising DRM asynchronously

    You may initialize the DRM asynchronously by creating and registering the
    MediaPlayer.OnDrmInfoListener for DRM preparation and the
    MediaPlayer.OnDrmPreparedListener to start out the participant.
    They work together with
    prepareAsync(), as proven beneath:

    Kotlin

    setOnPreparedListener()
    setOnDrmInfoListener()
    setDataSource()
    prepareAsync()
    // ...
    
    // If the information supply content material is protected you obtain a name to the onDrmInfo() callback.
    override enjoyable onDrmInfo(mediaPlayer: MediaPlayer, drmInfo: MediaPlayer.DrmInfo) {
        mediaPlayer.apply {
            prepareDrm()
            getKeyRequest()
            provideKeyResponse()
        }
    }
    
    // When prepareAsync() finishes, you obtain a name to the onPrepared() callback.
    // If there's a DRM, onDrmInfo() units it up earlier than executing this callback,
    // so you can begin the participant.
    override enjoyable onPrepared(mediaPlayer: MediaPlayer) {
        mediaPlayer.begin()
    }
    

    Java

    setOnPreparedListener();
    setOnDrmInfoListener();
    setDataSource();
    prepareAsync();
    // ...
    
    // If the information supply content material is protected you obtain a name to the onDrmInfo() callback.
    onDrmInfo() {
      prepareDrm();
      getKeyRequest();
      provideKeyResponse();
    }
    
    // When prepareAsync() finishes, you obtain a name to the onPrepared() callback.
    // If there's a DRM, onDrmInfo() units it up earlier than executing this callback,
    // so you can begin the participant.
    onPrepared() {
    
    begin();
    }
    

    Dealing with encrypted media

    Beginning with Android 8.0 (API degree 26) MediaPlayer also can decrypt
    Widespread Encryption Scheme (CENC) and
    HLS sample-level encrypted media (METHOD=SAMPLE-AES) for the elementary stream sorts
    H.264, and AAC. Full-segment encrypted media (METHOD=AES-128) was beforehand supported.

    Retrieving media from a ContentResolver

    One other characteristic that could be helpful in a media participant utility is the power to
    retrieve music that the consumer has on the system. You are able to do that by querying the ContentResolver for exterior media:

    Kotlin

    val resolver: ContentResolver = contentResolver
    val uri = android.supplier.MediaStore.Audio.Media.EXTERNAL_CONTENT_URI
    val cursor: Cursor? = resolver.question(uri, null, null, null, null)
    when {
        cursor == null -> {
            // question failed, deal with error.
        }
        !cursor.moveToFirst() -> {
            // no media on the system
        }
        else -> {
            val titleColumn: Int = cursor.getColumnIndex(android.supplier.MediaStore.Audio.Media.TITLE)
            val idColumn: Int = cursor.getColumnIndex(android.supplier.MediaStore.Audio.Media._ID)
            do {
                val thisId = cursor.getLong(idColumn)
                val thisTitle = cursor.getString(titleColumn)
                // ...course of entry...
            } whereas (cursor.moveToNext())
        }
    }
    cursor?.shut()
    

    Java

    ContentResolver contentResolver = getContentResolver();
    Uri uri = android.supplier.MediaStore.Audio.Media.EXTERNAL_CONTENT_URI;
    Cursor cursor = contentResolver.question(uri, null, null, null, null);
    if (cursor == null) {
        // question failed, deal with error.
    } else if (!cursor.moveToFirst()) {
        // no media on the system
    } else {
        int titleColumn = cursor.getColumnIndex(android.supplier.MediaStore.Audio.Media.TITLE);
        int idColumn = cursor.getColumnIndex(android.supplier.MediaStore.Audio.Media._ID);
        do {
           lengthy thisId = cursor.getLong(idColumn);
           String thisTitle = cursor.getString(titleColumn);
           // ...course of entry...
        } whereas (cursor.moveToNext());
    }
    

    To make use of this with the MediaPlayer, you are able to do this:

    Kotlin

    val id: Lengthy = /* retrieve it from someplace */
    val contentUri: Uri =
        ContentUris.withAppendedId(android.supplier.MediaStore.Audio.Media.EXTERNAL_CONTENT_URI, id )
    
    mediaPlayer = MediaPlayer().apply {
        setAudioAttributes(
            AudioAttributes.Builder()
                .setContentType(AudioAttributes.CONTENT_TYPE_MUSIC)
                .setUsage(AudioAttributes.USAGE_MEDIA)
                .construct()
        )
        setDataSource(applicationContext, contentUri)
    }
    
    // ...put together and begin...
    

    Java

    lengthy id = /* retrieve it from someplace */;
    Uri contentUri = ContentUris.withAppendedId(
            android.supplier.MediaStore.Audio.Media.EXTERNAL_CONTENT_URI, id);
    
    mediaPlayer = new MediaPlayer();
    mediaPlayer.setAudioAttributes(
        new AudioAttributes.Builder()
            .setContentType(AudioAttributes.CONTENT_TYPE_MUSIC)
            .setUsage(AudioAttributes.USAGE_MEDIA)
            .construct()
    );
    mediaPlayer.setDataSource(getApplicationContext(), contentUri);
    
    // ...put together and begin...
    

    Be taught extra

    These pages cowl subjects regarding recording, storing, and enjoying again audio and video.

    Leave a Reply

    Your email address will not be published.