简体   繁体   中英

Is there a way to play mp3 files in one mediaplayer object?

I can play a sound using Mediaplayer class in java android. I make a Mediaplayer object like this.

Mediaplayer mp=Mediaplayer.create(this,R.raw.mysong);

And then start it but what if i have more than one song and have to play it. Do I need to make objects for everyone of them. What i am trying to say is does Mediaplayer class have any kind of method or thing that i can clear the old song and put new song for playing?

Hope you get what i say

I could really appreciate it with a simple example.

Create only one object as you've done ,but like this

Mediaplayer mp = new MediaPLayer();

Change the data source: If your source it's a uri just pass it to setDataSource , but if is a resource in raw folder use this to create an uri from the resource

    int resourceId = R.raw.other_song

    uri uriSound = Uri.Builder()
        .scheme(ContentResolver.SCHEME_ANDROID_RESOURCE)
        .authority(resources.getResourcePackageName(resourceId))
        .appendPath(resources.getResourceTypeName(resourceId))
        .appendPath(resources.getResourceEntryName(resourceId))
        .build()

mp.setDataSource(this , uriSound)

Prepare and start the media player when you want

mp.prepare()
mp.start()

You create your mediaplayer object without ".create" like this Mediaplayer mp=new Mediaplayer(); Then you just set the source of it note the source must be in uri format mp.setDataSource(this,uri); But before starting it you have to prepare first like this: mp.prepare(); Then start. And when you wanted to change the source again first stop the mp then set another source Hope you get it.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM