Kevik
Kevik

Reputation: 9351

How to initialize MediaPlayer in android without an R.raw file

How do I initialize MediaPlayer in Android without an R.raw or some kind of file?

If I don`t initialize MediaPlayer with some file I will get a null pointer exception at runtime. But when the program is started there is no file path to use because the user has not yet pressed a button to select the mp3 file from the SD card.

When initialzing the Media Player there is another probem. It only takes an R.raw type file, not the path of a file from the SD card. And if I don't have any file in the R.raw directory then I can`t initialize with a file. It appears that you need an audio file in the local R.raw folder to do this.

 Mediaplayer player = MediaPlayer.create(this, R.raw.sample_music);

There is a method called "setDataSource" that allows me to set the path of the file, however I have to initialize the MediaPlayer first.

  player.setDataSource(selectedAudioPath);

Any other way to initialize MediaPlayer?

Upvotes: 3

Views: 5606

Answers (2)

JDevs
JDevs

Reputation: 101

This post helped me and the code below works as well:

Mediaplayer player = MediaPlayer.create(this, Uri.parse(File.getAbsolutePath()));

Upvotes: 1

Marcin S.
Marcin S.

Reputation: 11191

MediaPlayer mediaPlayer = new MediaPlayer();
mediaPlayer.setDataSource(filepath);

Upvotes: 8

Related Questions