Simple mediaplayer play mp3 from file path?
Asked Answered
M

7

40

I have a very simple mediaplayer that play background. It calls file from the apk, but I want it to play from any directory like as music or sdcard.

Here is my code:

private MediaPlayer mpintro;

.
.

mpintro = MediaPlayer.create(this, R.raw.intro);
        mpintro.setLooping(true);
        mpintro.start();
Manstopper answered 23/5, 2013 at 13:18 Comment(3)
@Johnsimit use Default Exception e.Marceline
It works like this: ` mpintro = MediaPlayer.create(this, Uri.parse(Environment.getExternalStorageDirectory().getPath()+ "/Music/intro.mp3")); mpintro.setLooping(true); mpintro.start();` It did not work properly as string filepath...Manstopper
@Johnsimit i have deployed my all mp3 files inside localhost/Android/music/vande.mp3 i used like hw u said Uri.parse(Environment.getExternalStorageDirectory().getPath()+ "//localhost/Android/Music/vande.mp3")); mpintro.setLooping(true); mpintro.start();` but it is not workingUninterested
M
65

It works like this:

mpintro = MediaPlayer.create(this, Uri.parse(Environment.getExternalStorageDirectory().getPath()+ "/Music/intro.mp3"));
mpintro.setLooping(true);
        mpintro.start();

It did not work properly as string filepath...

Manstopper answered 24/5, 2013 at 8:18 Comment(1)
we need to parse the path first became Uri. :DFluorine
M
26
String filePath = Environment.getExternalStorageDirectory()+"/yourfolderNAme/yopurfile.mp3";
mediaPlayer = new  MediaPlayer();
mediaPlayer.setDataSource(filePath);
mediaPlayer.prepare();   
mediaPlayer.start()

and this play from raw folder.

int resID = myContext.getResources().getIdentifier(playSoundName,"raw",myContext.getPackageName());

            MediaPlayer mediaPlayer = MediaPlayer.create(myContext,resID);
            mediaPlayer.prepare();
            mediaPlayer.start();

mycontext=application.this. use.

Marceline answered 23/5, 2013 at 13:25 Comment(4)
it says surround with try/catch, when I use filepath.. is it needed?Manstopper
@John simit every time any code u right use the try catch blosk it's good habit and good programing technic.Marceline
catch (IllegalArgumentException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (SecurityException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IllegalStateException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } it gives me whole catch code, is it enough to use Exception e or should I use what suggested to me?Manstopper
@Johnsimit simple exception. use only default exception. if helpful then click as correct mark.ok byeMarceline
P
4

Here is the code to set up a MediaPlayer to play off of the SD card:

String PATH_TO_FILE = "/sdcard/music.mp3";    
mediaPlayer = new  MediaPlayer();
mediaPlayer.setDataSource(PATH_TO_FILE);
mediaPlayer.prepare();   
mediaPlayer.start()

You can see the full example here. Let me know if you have any problems.

Ping answered 23/5, 2013 at 13:22 Comment(0)
L
3

Use the code below it worked for me.

MediaPlayer mp = new MediaPlayer();
mp.setDataSource("/mnt/sdcard/yourdirectory/youraudiofile.mp3");
mp.prepare();
mp.start();
Lubricate answered 23/5, 2013 at 13:21 Comment(5)
Environment.getExternalStorageDirectory() how can I use like this? Some times different devices may cause a problem width file path?Manstopper
@MD if you use this type path then some time sdcard name is different.and some device also have 10 gb plus internet memory so it's use as external memory.so this path can't work.Marceline
@Zala Janaksinh , This is just an example. I try to tell him, how it work. I am not implement her logic and her code.Lubricate
@MdAbdulGafur don't take personally i just advice.sorryMarceline
another android example: mp.setDataSource("/storage/emulated/0/Music/");Exist
U
2

I use this class for Audio play. If your audio location is raw folder.

Call method for play:

new AudioPlayer().play(mContext, getResources().getIdentifier(alphabetItemList.get(mPosition)
                        .getDetail().get(0).getAudio(),"raw", getPackageName()));

AudioPlayer.java class:

public class AudioPlayer {

    private MediaPlayer mMediaPlayer;

    public void stop() {
        if (mMediaPlayer != null) {
            mMediaPlayer.release();
            mMediaPlayer = null;
        }
    }
    // mothod for raw folder (R.raw.fileName)
    public void play(Context context, int rid){
        stop();

        mMediaPlayer = MediaPlayer.create(context, rid);
        mMediaPlayer.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
            @Override
            public void onCompletion(MediaPlayer mediaPlayer) {
                stop();
            }
        });

        mMediaPlayer.start();
    }

    // mothod for other folder 
    public void play(Context context, String name) {
        stop();

        //mMediaPlayer = MediaPlayer.create(c, rid);
        mMediaPlayer = MediaPlayer.create(context, Uri.parse("android.resource://"+ context.getPackageName()+"/your_file/"+name+".mp3"));
        mMediaPlayer.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
            @Override
            public void onCompletion(MediaPlayer mediaPlayer) {
                stop();
            }
        });

        mMediaPlayer.start();
    }

}
Unaccompanied answered 14/11, 2017 at 5:57 Comment(0)
R
1

2020 - NOV

This worked for me:

final File file = new File(getFilesDir(), "test.wav");//OR path to existing file
mediaPlayer = MediaPlayer.create(getApplicationContext(), Uri.fromFile(file));
mediaPlayer.start();
Robedechambre answered 19/11, 2020 at 6:53 Comment(0)
C
0

In Kotlin:

1) The file is in a resource folder :

var nowLesson =resources.getIdentifier("test.mp3", "raw", packageName)
             
mediaPlayer = MediaPlayer.create(applicationContext, nowLesson)
    
mediaPlayer.start()

2) The file is in a Path (file path)

val file = File(
        this.getDir("Music", MODE_PRIVATE),
        "/t.mp3"
    )
mediaPlayer = MediaPlayer.create(this,Uri.fromFile(file ))
                mediaPlayer.start()
Campy answered 4/2, 2022 at 10:49 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.