Android Mediaplayer Null point Exception (Java) - java

I am trying to create Mediaplayer session with given uri. but it causes NullpointerException.
Uri uri = Uri.parse(path);
// Creating MediaPlayer with given song's URI
if (mediaPlayer != null) {
mediaPlayer.stop();
mediaPlayer.release();
}
mediaPlayer = MediaPlayer.create(this, uri);
try {
// Setting the MediaPlayer Listener
mediaPlayer.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
#Override
public void onPrepared(MediaPlayer mp) {
seekBar.setMax(mp.getDuration());
mediaPlayer.start();
changeSeekbar();
}
});
} catch (Exception e) {
Log.e("ERROR", e.toString());
}
Given Logcat:
2020-04-07 22:21:05.289 12237-12237/com.example.musicappresearch2 E/Path: /storage/emulated/0/Music/Alone - Viren.mp3
2020-04-07 22:21:05.289 12237-12237/com.example.musicappresearch2 E/ERROR: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.media.MediaPlayer.setOnPreparedListener(android.media.MediaPlayer$OnPreparedListener)' on a null object reference
Could you Tell me What i am doing wrong ? Thanks.

There are two ways to write this code, both tested on the device
First of all, make sure you handle android.permission.READ_EXTERNAL_STORAGE correctly and you really have correct Uri.
MediaPlayer.create(this, uri); will fail if either context or uri are invalid.
MediaPlayer.create(this, uri); which itself already prepares player so you don't need .prepareAsync() in this situation. and your code is good to go.
another way:
mediaPlayer = new MediaPlayer(); // hence, we don't use .create, manually instantiate
try {
mediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
mediaPlayer.setDataSource(this, uri);
mediaPlayer.setOnPreparedListener(mp -> {
mediaPlayer.start();
});
/* use async, if you don't want to block UI thread
keep in mind, this should be called after setting listener
because it might prepare even until the listener has been set */
mediaPlayer.prepareAsync();
} catch (Exception e) {
Log.e("ERROR", e.toString());
}

Try this :
Uri uri = Uri.parse(path);
mediaPlayer = new MediaPlayer();
try {
// mediaPlayer.setDataSource(String.valueOf(uri));
mediaPlayer.setDataSource(MainActivity.this,uri);
} catch (IOException e) {
e.printStackTrace();
}
try {
mediaPlayer.prepare();
} catch (IOException e) {
e.printStackTrace();
}
mediaPlayer.start();

Related

IllegalStateException in MediaPlayer

Here is my code
if (player != null) {
if(player.isPlaying()){
player.pause();
player.stop();
}
player.release();
}
and here is error
FATAL EXCEPTION: main
java.lang.IllegalStateException
at android.media.MediaPlayer.isPlaying(Native Method)
at com.mindefy.sindhipathshala.RecViewAdapter.mediafileRelease(RecViewAdapter.java:234)
at com.mindefy.sindhipathshala.SectionFruits.onBackPressed(SectionFruits.java:252)
I am a beginner in Android and i am very confused with the lifecycle of a MediaPlayer.
This is a function in an adapter that is called from onBackPressed() function of another Activity. player is a class variable.
I am releasing this MediaPlayer in same file as
public void onClick(View v) {
try {
if (player != null) {
player.stop();
player.release();
}
} catch (Exception e) {
}
player = MediaPlayer.create(activityContext, soundId);
player.start();
}
The problem is you don't keep track of the state of your MediaPlayer instance.
Before calling isPlaying() you only perform a null value check, although player can still be released (but not null).
Calling isPlaying() on a released MediaPlayer instance will result in an IllegalStateException.
To avoid this, you could for example set player to null when you release it:
player.release();
player = null;
Or you could use a boolean flag to keep track of its state:
boolean isReleased;
// ...
player.release();
isReleased = true;
So you could check for this flag when necessary:
if (player != null && !isReleased) {
if(player.isPlaying()) {
// ...
}
}
(don't forget to set it to false when appropriate)
Adding to earthW0rmjim: I was facing the same issue (some audios didn't reproduce because of an ilegal state exception). What I found is that I was reseting my audio object on a callback. So, I was setting player.setDataSource(url) before I reset my object, because the callback was doing it after. My solution: player.reset() on the try / catch block of setDataSource and prepareAsync.
try {
player.reset(); //Important line
player.setDataSource(url);
player.prepareAsync();
} catch (Exception e) {
Log.e(Constants.AUDIO_LOG_TAG, "Error playing file " + url, e);
}
And look at the callback:
public void finishedPlayback(){
player.reset(); //Executing after the try / catch (sometimes)
}

stream a live audio stream for android

I am new to android programming and therefore this might seem like an easy question for many but its been 2 days and i have searched almost everywhere on the internet but cant find a solution to my problem
i am trying to stream a link(which works when i post on chrome) using MediaPlayer class. Although i get audio on chrome, i never get anything when i run the app on my Samsung galaxy s4.i have already used internet permission for the app. here is the code i am using:
public class LiveKirtan extends Activity {
MediaPlayer mp;
String url;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_live_kirtan);
url = "http://radio2.sikhnet.com:8020/live";
Uri myUri = Uri.parse(url);
mp = new MediaPlayer();
try {
mp.setDataSource(this, myUri);
} 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();
}
mp.setAudioStreamType(AudioManager.STREAM_MUSIC);
mp.prepareAsync();
mp.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
#Override
public void onPrepared(MediaPlayer player) {
player.start();
}
});
}
}
Make sure to add the following permission to your manifest:
<uses-permission android:name="android.permission.INTERNET"/>
Also, Android does not support just any kind of streaming audio (especially pre kitkat), so make sure to check the compatibility of your stream here.

Can't use STREAM_VOICE_CALL to play audio via MediaPlayer in android java

I have tried to play many audio (mp3) files through MediaPlayer's setAudioStreamType(AudioManager.STREAM_VOICE_CALL); but mp.start(); does not play nor does it throw an exception.
The setup works with SoundPool but it is limited to like 5 seconds, some files playing upto 8 seconds.
I am attaching the part of code here:
String s = absolutepath.get(position);
Uri u = Uri.parse(s);
playing = (MediaPlayer) MediaPlayer.create(MainActivity.this, u);
playing.setOnPreparedListener(this);
onPrepared includes this:
#Override
public void onPrepared(MediaPlayer mp) {
// TODO Auto-generated method stub
spProgress.cancel();
mp.setAudioStreamType(AudioManager.STREAM_VOICE_CALL);
try {
mp.start();
} catch (IllegalStateException e) {
Toast.makeText(this, "exception", Toast.LENGTH_SHORT).show();
}
}
I have tried this without the try/catch and even without listener. The only time it plays is when I don't use the stream type STREAM_VOICE_CALL.
The same files can be played with SoundPool:
SoundPool sp = new SoundPool(1, AudioManager.STREAM_VOICE_CALL, 0);
sp.load(s, 1);
sp.setOnLoadCompleteListener(this);
Listener:
#Override
public void onLoadComplete(SoundPool soundPool, int sampleId, int status) {
// TODO Auto-generated method stub
if (status == 0) {
spProgress.cancel();
sp.play(sampleId, 1, 1, 1, 0, 1);
} else {
Toast.makeText(this, "failed to load", Toast.LENGTH_SHORT).show();
}
}
I actually had the same problem, and Google's Guide is very bad here - it's indeed a bit tricky, but simple to explain:
As you need to change the STREAM, and then prepare() your MediaPlayer again, you'll get it working by doing this:
Resources res = getResources();
AssetFileDescriptor afd = res.openRawResourceFd(R.raw.tts_a);
mp = new MediaPlayer();
//mp.reset();
mp.setAudioStreamType(AudioManager.STREAM_VOICE_CALL);
mp.setLooping(false);
try {
mp.setDataSource(afd.getFileDescriptor(), afd.getStartOffset(), afd.getLength());
mp.prepare();
} catch (IOException e) {
e.printStackTrace();
}
mp.start();
The actual trick is to NOT use the MediaPlayer.create, as it's calling the prepare itself! Therefore you're not able to set the Stream. By setting the File with AssetFileDescriptor, you can set the Stream and call your prepare() afterwards!

android media player wont play audio file

im making a music app just for fun. I can read all my music files from sd card but MediaPlayer wont play the sound. I have the path to the file which i pass to the media player with setDataSource but nothing happens and i get no exceptions. Here is the code im using.
Uri songUri;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_player);
setUpViews();
MediaPlayer mp = new MediaPlayer();
try {
mp.setDataSource(songUri.toString());
mp.prepare();
} catch (IllegalArgumentException e) {
Toast.makeText(this, "ILLEGAL ARGUMENT EXCEPTION", Toast.LENGTH_LONG).show();
e.printStackTrace();
} catch (SecurityException e) {
Toast.makeText(this, "SECURITY EXCEPTION", Toast.LENGTH_LONG).show();
e.printStackTrace();
} catch (IllegalStateException e) {
Toast.makeText(this, "ILLEGAL STATE EXCEPTION", Toast.LENGTH_LONG).show();
e.printStackTrace();
} catch (IOException e) {
Toast.makeText(this, "IO EXCEPTION", Toast.LENGTH_LONG).show();
e.printStackTrace();
}
mp.start();
Log.d("URI AFTER SET UP", songUri.toString());
}
As i said before nothing happens when i open this activity but i still get all the Log.d in the console. Is there any more configurations for the media player to play the music? Thanks in advance.
setDataSource() requires a path argument . You are passing the entire uri as string. Try this :
mp.setDataSource(songUri.getPath());
mp.prepare();
mp.start();
Moreover, if you are trying to access a file with content:// uri, it won't work. You'll have to find the real path to the file, i.e file:// uri.
I think you have to add setAudioStreamType to your MediaPlayer Object. You can add this before mp.setDataSource(your_URI); like below
mp.setAudioStreamType(AudioManager.STREAM_MUSIC);
There other types, you can choose AudioManager.STREAM_MUSIC for Music Player
I just solved the problem, and i just dont know why it works. What i did was to put a button to stop the music being played. I dont understand why it works so if someone could explain why it does i'd be thanksfull.
get the path of song by querying MEDIASTORE-EXTERNAL_URI.And this field MEDIASTORE.AUDIO.MEDIA.DATA will give u the path of the song(which is string). U can set it directly to mediaplayer.setDataSource(Your_path_from_mediastore) .It will work fine than.

enquiry about MediaPlayer.setDatasource(URL);

I'm a Beginner in android programming and I want to programming mp3 app to call some mp3 files from URL, so when I show "Media Player" in android developer I put the URL in the setDataSource and it's work fine, but the problem is the Activity take a lot of time to display it and in the sometimes app will be crashed. This is the part of my code :
file_url = Mp3_Linkes[num];
//Set Source
try {
mp.setDataSource(file_url);
} catch (Exception e) {
Toast.makeText(this, "Source Error !!", Toast.LENGTH_LONG).show();
}
//Prepare
try {
mp.prepare();
}catch(Exception e)
{
Toast.makeText(this, "Prepare Error !!", Toast.LENGTH_LONG).show();
}
//Start
mp.start();
Your activity is blocking because you are calling prepare on your Main Thread (UI thread)
Instead You can use prepareAsynch and OnPreparedListener to start specially when loading from remote source:
code :
try {
mp.setDataSource(file_url);
mp.setOnPreparedListener(new OnPreparedListener() {
public void onPrepared(MediaPlayer player) {
player.start();
}
});
mp.prepareAsync();

Categories