This is my code, I want to keep music playing when the app is in background. And I want to be able to pause it when I re-open the app. The music should play in the background, but for some reason media player returns null pointer when I re-open it. So, when I pause it, it crashes.
public void play(View view) {
if (status) {
status = false;
requestRecordAudioPermission();//audio permission
startPlay();//start mediaplayer
} else {
status = true;
mediaPlayer.pause();
}
}
public void startPlay() {
mediaPlayer = new MediaPlayer();
try {
mediaPlayer.setDataSource(URL_LINK);
mediaPlayer.prepare();
} catch (IOException e) {
e.printStackTrace();
Toast.makeText(HomeActivity.this, "CAN'T PLAY!",Toast.LENGTH_LONG).show();
}
mediaPlayer.start();
}
Why Media Player returns null after pressing the home button and reopening the app?
Thanks for help
If you are streaming audio from an url then try to load the Media Player asynchronously.
String url = "YOUR_URL";
MediaPlayer myMediaPlayer = new MediaPlayer();
myMediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
try {
myMediaPlayer.setDataSource(url);
myMediaPlayer.prepareAsync();
} catch (IOException e) {
Toast.makeText(this, "mp3 not found", Toast.LENGTH_SHORT).show();
}
myMediaPlayer.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
#Override
public void onPrepared(MediaPlayer player) {
player.start();
}
});
Related
Opening app without any error. But can't play music. But can play music from local machine. Internet connection is fine.
I have enabled internet permission in AndroidManiFest.xml
<uses-permission android:name="android.permission.INTERNET" />
I have enabled http permission.
android:usesCleartextTraffic="true"
MediaPlayer mediaPlayer = new MediaPlayer();
try {
mediaPlayer.setDataSource("http://penguinradio.dominican.edu/Sound%20FX%20Collection/Motorbike.mp3");
} catch (IOException e) {
e.printStackTrace();
}
mediaPlayer.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
#Override
public void onPrepared(MediaPlayer mP) {
Toast.makeText(MainActivity.this, "Ready to Play", Toast.LENGTH_SHORT).show();
mP.start();
}
});
mediaPlayer.prepareAsync();
Full Code:
https://paste.ubuntu.com/p/dsjbg7YMNn/
I have tested your code and sometimes it works, sometimes it doesn't. If you search on Stack Overflow you will find plenty of similar problems.
You have 2 options:
Migrate to ExoPlayer2 which is far superior that MediaPlayer.
It doesn't work to play the sound in OnPreparedListener, but you can play it on button click, after it's prepared:
public class MainActivity extends AppCompatActivity {
private Button streamButton;
private boolean isPrepared = false;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
MediaPlayer mediaPlayer = new MediaPlayer();
try {
mediaPlayer.setDataSource("http://penguinradio.dominican.edu/Sound%20FX%20Collection/Motorbike.mp3");
} catch (IOException e) {
e.printStackTrace();
}
mediaPlayer.setOnPreparedListener(mp -> {
Toast.makeText(MainActivity.this, "Ready to Play", Toast.LENGTH_SHORT).show();
isPrepared = true;
streamButton.setVisibility(View.VISIBLE);
});
mediaPlayer.setOnCompletionListener(mp -> {
mp.release();
isPrepared = false;
streamButton.setVisibility(View.INVISIBLE);
});
mediaPlayer.prepareAsync();
streamButton = findViewById(R.id.streamButton);
streamButton.setOnClickListener(v -> {
if (isPrepared) {
mediaPlayer.start();
}
});
}
}
try this:
if(mediaPlayer != null ){
if (mediaPlayer.isPlaying()){mediaPlayer.stop();}
mediaPlayer.reset(); //this line is important!
String path = File.separator + "sdcard" + File.separator + utilsFields.repoDirRoot + File.separator + media.mp4;
try {
mediaPlayer.setDataSource(path);
}catch (Exception ignored){}
try {
mediaPlayer.prepare();
}catch (Exception ignored){}
mediaPlayer.start();
}
I have been able to play audio from my firebase storage and i want the song to stop and start when a user clicks on same button but i haven't been able to get get the right code for that.
this is what i have tried
MediaPlayer mediaPlayer = new MediaPlayer();
try {
mediaPlayer.setDataSource(url);
mediaPlayer.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
#Override
public void onPrepared(MediaPlayer mediaPlayer) {
if (!mediaPlayer.isPlaying()) {
mediaPlayer.start();
}else {
mediaPlayer.stop();
}
}
});
mediaPlayer.prepare();
} catch (IOException e) {
e.printStackTrace();
}
The above code is correct, now do one thing create button listener and write below code
button.setOnClickListener(view.onCLickListeners(){
#override
public void onClick(){
if (!mediaPlayer.isPlaying()) {
mediaPlayer.play();
}
else {
mediaPlayer.pause();
}
}});
And please define mediaplayer globally.
in my simple player i have play, and stop buttons and play and pause media player work fine, now after click on stop and play again, media player don't work and i'm not sure whats problem to resolve that
#Nullable
#Override
public View onCreateView(#NonNull LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
...
playMonthLesson();
...
}
#SuppressLint("DefaultLocale")
public void playMonthLesson() {
try {
mediaPlayer.reset();
mediaPlayer.setDataSource(CoreApplication.MEDIAFOLDER + "/" + lesson.getFilename());
mediaPlayer.prepare();
mediaPlayer.start();
lesson_play.setImageResource(R.drawable.ic_pause);
int totalDuration = mediaPlayer.getDuration();
// set Progress bar values
lesson_progress_bar.setProgress(curretLessonProgress);
lesson_progress_bar.setMax(100);
// Updating progress bar
updateProgressBar();
} catch (IllegalArgumentException e) {
e.printStackTrace();
} catch (IllegalStateException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
#OnClick(R.id.lesson_play)
public void lesson_play(View view) {
if (mediaPlayer == null) {
playMonthLesson();
} else if (mediaPlayer.isPlaying()) {
if (mediaPlayer != null) {
mediaPlayer.pause();
// Changing button image to play button
lesson_play.setImageResource(R.drawable.ic_play);
}
} else {
// Resume song
if (mediaPlayer != null) {
mediaPlayer.start();
// Changing button image to pause button
lesson_play.setImageResource(R.drawable.ic_pause);
}
}
}
#OnClick(R.id.lesson_stop)
public void setLesson_stop(View view) {
if (mediaPlayer != null) {
mediaPlayer.stop();
lesson_play.setImageResource(R.drawable.ic_play);
lesson_progress_bar.setProgress(0);
}
}
According to the MediaPlayer life cycle, which you can view in the Android API guide, I think that you have to call reset() instead of stop(), and after that prepare again the media player (use only one) to play the sound from the beginning. Take also into account that the sound may have finished. So I would also recommend to implement setOnCompletionListener() to make sure that if you try to play again the sound it doesn't fail.
The problem is that when you stop mediaplayer and click on play again your call will go to mediaplayer.play() as mediaplayer is not null.
You will have to null the mediaPlayer on stop method. Now, once you stop mediaplayer and again click on play it will call playMonthLesson();
#OnClick(R.id.lesson_stop)
public void setLesson_stop(View view) {
if (mediaPlayer != null) {
mediaPlayer.stop();
mediaPlayer.reset();
mediaPlayer = null;
lesson_play.setImageResource(R.drawable.ic_play);
lesson_progress_bar.setProgress(0);
}
}
change this code too,
#SuppressLint("DefaultLocale")
public void playMonthLesson() {
try {
mediaPlayer = new MediaPlayer();
mediaPlayer.reset();
mediaPlayer.setDataSource(CoreApplication.MEDIAFOLDER + "/" + lesson.getFilename());
mediaPlayer.setOnPreparedListener(new OnPreparedListener(){
#Override
public void onPrepared(MediaPlayer mp) {
mp.start();
lesson_play.setImageResource(R.drawable.ic_pause);
int totalDuration = mediaPlayer.getDuration();
}
});
mediaPlayer.prepareAsync();
// set Progress bar values
lesson_progress_bar.setProgress(curretLessonProgress);
lesson_progress_bar.setMax(100);
// Updating progress bar
updateProgressBar();
} catch (IllegalArgumentException e) {
e.printStackTrace();
} catch (IllegalStateException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
How can i replay a .mp3 in my app? I can't replay the mp3 using the start method
Here is the code segment :
mMediaPlayer = MediaPlayer.create(MainActivity.this, R.raw.splashsound);
mMediaPlayer.setLooping(true);
Button myButtonOne = (Button) findViewById(R.id.songon);
myButtonOne.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
mMediaPlayer.start();
}
});
Button myButtonTwo = (Button) findViewById(R.id.songoff);
myButtonTwo.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
if(mMediaPlayer.isPlaying()){
//mMediaPlayer.stop();
mMediaPlayer.release();
mMediaPlayer = null;
}
}
});
Can anyone please tell me what i am doing wrong here?
If you want to replay the mp3 why do release and set to null your media player?
I guess that is your problem!
Just stop and start it again without releasing your media player instance.
To replay mp3 track try this:
private void playSong(int songIndex) {
// Play song
try {
mp.reset();
mp.setDataSource(songsList.get(songIndex).get("songPath"));
mp.prepare();
mp.start();
} catch (IllegalArgumentException e) {
e.printStackTrace();
} catch (IllegalStateException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
Or without calling reset():
mediaPlayer.setLooping(true);
I have the following code to play an mp3 file from the web and this is working but when I use the stop functionality the audio does not stop. Can anyone point me towards a resource to find out more about this or tell me where I am going wrong? Thanks.
showAudio.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
MediaPlayer mediaPlayer = new MediaPlayer();
mediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
if (!showAudio.getText().equals("Stop")) {
try {
String url = lblAudio.getText().toString();
if (url.length() > 2) {
mediaPlayer.setDataSource(url);
mediaPlayer.prepare();
mediaPlayer.start();
showAudio.setText("Stop");
}
} catch (Exception e) {
Toast.makeText(getBaseContext(), "Sorry, there was a problem playing audio.", Toast.LENGTH_SHORT).show();
}
} else {
try {
mediaPlayer.stop();
mediaPlayer.release();
} catch (Exception ex) {
ex.printStackTrace();
}
showAudio.setText("Audio");
}
}
});
You are creating a new MediaPlayer every time you click the button. Create the player outside of the click handler.
Try out :
try {
if(mediaPlayer.isPlaying())
{
mediaPlayer.stop();
mediaPlayer.release();
}
} catch(Exception ex) {
ex.printStackTrace();
}
Try making your media player a global variable and make it static....
I have a working media player that starts and stops
Uri ringtone;
MediaPlayer mp;
ringtone = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_RINGTONE);
mp = MediaPlayer.create(getApplicationContext(), ringtone);
//code to start the mediaplayer
if (Flags.notificationReceived) {
showAlert(Flags.patientModel);
Flags.notificationReceived = false;
mp.start();
mp.setLooping(true);
vibrate(2000);
}
//code to stop the media player
if (mp.isPlaying()) {
mp.stop();
mp.reset();
mp.release();
mp = MediaPlayer.create(getApplicationContext(), ringtone);
}