play the sound again when the user get back to activity - android

what i have is an activity which i play some sound each the user open it , but when he got to the child activity of it .. it stops as i want .. but i want the user when he press back button and return to this activity (which is parent activity) to play this sound again ... how can i do this .. here is some of my code:
public class GeneralScreen extends Activity {
String mytext="";
MediaPlayer mMediaPlayer;
protected static final int RESULT_SPEECH = 1;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.general_screen);
GridView g = (GridView) findViewById(R.id.myGrid);
mMediaPlayer = new MediaPlayer();
mMediaPlayer = MediaPlayer.create(this, R.raw.selecteng);
mMediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
mMediaPlayer.setLooping(false);
mMediaPlayer.start();
mMediaPlayer.setOnCompletionListener(new OnCompletionListener() {
public void onCompletion(MediaPlayer mp) {
Log.i("Completion Listener","Song Complete");
Toast.makeText(GeneralScreen.this, "Media Completed", Toast.LENGTH_SHORT).show();
Intent intent = new Intent(RecognizerIntent.ACTION_RECOGNIZE_SPEECH); //for open google API
intent.putExtra(RecognizerIntent.EXTRA_LANGUAGE_MODEL, RecognizerIntent.LANGUAGE_MODEL_FREE_FORM);
intent.putExtra(RecognizerIntent.EXTRA_LANGUAGE_MODEL, "en-US"); //for transfer voice from google API to text in EditText
try {
startActivityForResult(intent, RESULT_SPEECH); // for get result
} catch (ActivityNotFoundException a) {
Toast t = Toast.makeText(getApplicationContext(), //if make error get this message
"Ops! Your device doesn't support Speech to Text",
Toast.LENGTH_SHORT);
t.show();
}
}
});

Just create a method playYourMusic() and put all the code to start mediaplayer inside. Then put the playYourMusic into onRestart and in onCreate():
#Override
protected void onRestart() {
playYourMusic();
super.onRestart();
}
Think on it, to finish the activity that You are leaving when You will go back to main. So, why not in onResume()? Because onResume() is also called at the start of Activity. Some devices handle the LifeCycle of android in a different way.

You just use following methods #Override
protected void onResume() {
// TODO Auto-generated method stub
super.onResume();
//play music code here
}
#Override
protected void onPause() {
// TODO Auto-generated method stub
super.onPause();
//stop music code here
}

You need to execute your playSound() method in the appropriate lifecycle method (in this case I think it would likely be onResume() ).
Understanding the Activity lifecycle is very fundamental, and important to understand, please check the following resource for more information:
http://developer.android.com/training/basics/activity-lifecycle/index.html

Related

Changing audio button from play to pause when clicked and vice versa

I want a play button in my app that when clicked plays the audio and changes to pause, and when the pause button is clicked the audio stops and the button changes to play again and so on. But the button is not working as expected. Please help. I'm adding my java code below.
public class surah extends AppCompatActivity {
MediaPlayer mp = new MediaPlayer();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_surah);
mp=MediaPlayer.create(surah.this, R.raw.surahkahf);
final ImageView audio = (ImageView)findViewById(R.id.btn);
audio.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if(mp.isPlaying()){
mp.stop();
audio.setBackgroundResource(R.drawable.play);
try {
mp.prepare();
}catch (IllegalStateException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
else {
mp.start();
audio.setImageResource(R.drawable.pause);
}
}
});
}
}
Use audio.setImageResource(R.drawable.play) instead of audio.setBackgroundResource(R.drawable.play). Use mp.pause() instead of mp.stop();
First, as aborocz mentions in comments, you probably intend to pause playback instead of stop it, so the method you want to use is pause(). In that case you would not need to prepare the MediaPlayer again, and it will start from the same place it was paused when playback is resumed.
Second, the isPlaying() method is not particularly appropriate for this purpose. There are race conditions that prevent the desired behavior. From the Android MediaPlayer documentation:
Note that the transition from the Started state to the Paused state
and vice versa happens asynchronously in the player engine. It may
take some time before the state is updated in calls to isPlaying(),
and it can be a number of seconds in the case of streamed content.
Instead, store your own boolean value.
public class surah extends AppCompatActivity {
private MediaPlayer mp;
private boolean isMediaPlaying = false;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_surah);
mp = MediaPlayer.create(surah.this, R.raw.surahkahf);
final ImageView audio = (ImageView)findViewById(R.id.btn);
audio.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (isMediaPlaying) {
mp.pause();
audio.setBackgroundResource(R.drawable.play);
isMediaPlaying = false;
} else {
mp.start();
audio.setImageResource(R.drawable.pause);
isMediaPlaying = true;
}
}
});
}
}

How to set Android background music playing only one time

I am creating a game, I want to play a background music for one activity only(For main menu of game), my code shown below, The problem is that the music plays more than one time, I want to play the same music also when activity Resumes.
public class Menu extends Activity {
MediaPlayer mp
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.menu);
mp = MediaPlayer.create(Menu.this, R.raw.adalante);
if(!mp.isPlaying()) {
mp.start();
}
public void play(View ButtonClicked) {
mp.stop();
mp.release();
//mp = MediaPlayer.create(Menu.this, R.raw.l);
//mp.start();
goToActivity(Game.class);
}
#Override
public void onResume() {
super.onResume(); // Always call the superclass method first
//coins
coin.setText(data.getString("coin"));
mp = MediaPlayer.create(Menu.this, R.raw.adalante);
if(!mp.isPlaying()) {
mp.start();
}
//mps.release();
}
In your onResume don't initialise MediaPlayer again and again. It creates new instance every time when you come to onResume. So add a check in onResume like this :
#Override
protected void onResume() {
super.onResume();
if (mp==null)
mp=MediaPlayer.create(MainActivity.this,R.raw.adalante);
if (!mp.isPlaying())
mp.start();
}
and additionally add this for prevention to play when activity goes to onPause
#Override
protected void onPause() {
super.onPause();
mp.pause();
}

How make a Button on/off music android

i'am trying to develop an app in android with 2 buttons. the first button must pause and restart the music if you state is on or off. but this code doesn't works, why?
public class MainActivity extends Activity {
MediaPlayer sound;
Boolean pulsado=false;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
this.setVolumeControlStream(AudioManager.STREAM_MUSIC);
sound=MediaPlayer.create(getBaseContext(),R.raw.gaitas);
sound.setLooping(true);
sound.start();
}
public void boton1(View v){
if(pulsado==false){
sound.stop();
pulsado=true;
}else{
sound.reset();
}
}
public void boton2(View v){
Intent i=new Intent(this,ActivityB.class);
startActivity(i);
}
Android documentation says about MediaPlayer.reset() -- Resets the MediaPlayer to its uninitialized state. After calling this method, you will have to initialize it again by setting the data source and calling prepare().
For your purpose, you could use MediaPlayer.create(...) again to setDataSource to the MP and prepare it for playing.
if (pulsado == false) {
sound.stop();
sound.reset();
pulsado = true;
} else {
sound = MediaPlayer.create(getBaseContext(), R.raw.song);
sound.setLooping(true);
sound.start();
pulsado = false;
}
If you are looking for pausing the song, you could rather call sound.pause() and in else block simple sound.start() should be enough to resume the song.

How to play music again when returing to main activity

What I would like to achieve is to stop the music when I go to my 2nd activity from my main activity (this works and the music does stop) But when I press the back button to go back to the main activity the music doesn't seem to start again. How can I make it to start again or if possible pause to music when going to the 2nd activity and resume when going back to the main activity.
Here is my code where the music stops when going to the next activity but doesn't play when going back to the main activity:
public class MainActivity extends Activity implements OnClickListener{
public static MediaPlayer player;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
player = new MediaPlayer();
player = MediaPlayer.create(this, R.raw.music_a);
player.setAudioStreamType(AudioManager.STREAM_MUSIC);
player.setLooping(true);
player.start();
Button btn = (Button) findViewById(R.id.button1);
btn.setOnClickListener(new View.OnClickListener()
{
public void onClick(View v) {
Intent intent = new Intent(MainActivity.this, SecondActivity.class);
startActivity(intent);
player.stop();
}
});
}
protected void onPause() {
if (this.isFinishing()){
player.stop();
Toast.makeText(MainActivity.this, "BYE", Toast.LENGTH_LONG).show();
}
Context context = getApplicationContext();
ActivityManager am = (ActivityManager) context.getSystemService (Context.ACTIVITY_SERVICE);
List<RunningTaskInfo> taskInfo = am.getRunningTasks(1);
if (!taskInfo.isEmpty()) {
ComponentName topActivity = taskInfo.get(0).topActivity;
if (!topActivity.getPackageName().equals(context.getPackageName())) {
player.stop();
}
else {
}
}
super.onPause();
}
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
}
}
And here is my 2nd activity (do I need to put something here as well?)
public class SecondActivity extends Activity{
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.secondscreen);
}
}
Thanks
You have to call onResume on your First Activity to continue playing music
#Override
protected void onPause() {
super.onPause();
// stop the music
}
#Override
protected void onResume() {
super.onResume();
// play the music here
}
just remove your code to play from oncreate and start playing song in onResume
try {
if (player != null) {
player.start();
} else {
player = new MediaPlayer();
player = MediaPlayer.create(this, R.raw.meintenu);
player.setAudioStreamType(AudioManager.STREAM_MUSIC);
player.setLooping(true);
player.start();
}
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
edit:
write this in your button click
Intent intent = new Intent(MainActivity.this,SecondActivity.class);
startActivity(intent);
player.stop();
player.release();
player=null;
pause Your music when you go to next activity and get the current position of the music
homeMusic.pause();
position=homeMusic.getCurrentPosition();
then add onRestart method,
#Override
protected void onRestart() {
super.onRestart();
homeMusic.seekTo(position);
homeMusic.start();
homeMusic.setLooping(true);
}

Media Player start stop start

I am making a new android sound application. I made a clickable button to play sound when I click on it. But I also want it to stop playing sound when I click for the second time. That part works fine now here is the problem, when I click again on button to play sound again, it doesn't play it, Media player is completely stopped. I was looking on forums but I can't seem to find an answer that could help me.
Here is my Activity:
MediaPlayer mpButtonClick1;
MediaPlayer mpButtonClick2;
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.prvi);
final MediaPlayer mpButtonClick1 = MediaPlayer.create(this, R.raw.spalshm);
final MediaPlayer mpButtonClick2 = MediaPlayer.create(this, R.raw.splashs);
Button dugme = (Button) findViewById(R.id.dugme);
dugme.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (mpButtonClick1.isPlaying()) {
mpButtonClick1.stop();
mpButtonClick1.reset();
}
else {
mpButtonClick1.start();
}
}
});
When I try to write mpButtonClick1.prepare(); I get error Unhandled Exception Type IOE exception
Try to use pause instead of stop.
Reason: if you pause the MediaPlayer, then you can resume it later. However, if you use stop, almost any other method won't work and you will have to prepare the MediaPlayer again (or create a new one).
More info: here and here
PS: don't forget to release the memory when you finish using the resources.
Try this:
You should use only one mediaplayer object
public class PlayaudioActivity extends Activity {
private MediaPlayer mp;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
Button b = (Button) findViewById(R.id.button1);
Button b2 = (Button) findViewById(R.id.button2);
final TextView t = (TextView) findViewById(R.id.textView1);
b.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
stopPlaying();
mp = MediaPlayer.create(PlayaudioActivity.this, R.raw.far);
mp.start();
}
});
b2.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
stopPlaying();
mp = MediaPlayer.create(PlayaudioActivity.this, R.raw.beet);
mp.start();
}
});
}
private void stopPlaying() {
if (mp != null) {
mp.stop();
mp.release();
mp = null;
}
}
}
Change your class with below code:
remove reset();.
init well all components:
MediaPlayer mpButtonClick1;
MediaPlayer mpButtonClick2;
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.prvi);
mpButtonClick1 = MediaPlayer.create(this, R.raw.spalshm);
mpButtonClick2 = MediaPlayer.create(this, R.raw.splashs);
Button dugme = (Button) findViewById(R.id.dugme);
dugme.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (mpButtonClick1.isPlaying()) {
mpButtonClick1.stop();
}
else {
mpButtonClick1.start();
}
}
});
You're calling mpButtonClick1.reset() after mpButtonClick1.stop() - don't do that:
if (mpButtonClick1.isPlaying()) {
mpButtonClick1.stop();
mpButtonClick1.reset(); //<--------- calling reset(), remove this line
}
The docs for reset() say:
Resets the MediaPlayer to its uninitialized state. After calling this method, you will have to initialize it again by setting the data source and calling prepare().
Remove mpButtonClick1.reset() and it should work.
Keep in mind that MediaPlayer works as a state machine, which means that if you call methods in the wrong order, you'll get problems. Please read about MediaPlayer here and here.
Hey please use following
for stop -> media player
mp.seekTo(0);
mp.pause();
again for start just call
mp.start();
In my experience when I need to play multiple times and I may need to stop one play to start another play, (like in the case of multiple buttons), I just create another player, making sure that I release the resources for the previous one. To stop just use
mediaPlayer.stop();
But for play use something like this (adapt the logging to your specific needs) to create/recreate your player:
private boolean createMediaPlayer()
{
if (mediaPlayer!=null)
{
if(mediaPlayer.isPlaying())
{
mediaPlayer.stop();
mediaPlayer.reset();
mediaPlayer.release();
mediaPlayer=null;
}
}
mediaPlayer = new MediaPlayer();
mediaPlayer.setVolume(1f, 1f);
try
{
mediaPlayer.setAudioStreamType(Interop.PRIMARY_STREAM);
mediaPlayer.setDataSource(m_soundFile);
mediaPlayer.prepare();
return true;
// Interop.logDebug(TAG + "-loadAudio: SUCCESS" + m_soundFile);
} catch (Exception e)
{
Interop.logError(TAG + "-LoadAudio for Clic Sound: audioPlayer prepare failed for current file: " + m_soundFile);
Interop.logError(TAG + "-Exception: " , e);
return false;
}
}
and than use
if (createMediaPlayer())
mediaPlayer.start();
this will ensure proper release of the resources used by the media player.
A simple solution is to Use pause instead of stop and the seek to the beginning of the song.
I know that this question is quite old but recently while learning Android, I also got stuck at this point and found a very simple solution which I'd like to share with everyone.
Instead of trying to stop or reset the media, you can just seek back to the starting position.
mediaPlayer.seekTo(0);
For reference, I am also posting my code below:
public class MainActivity extends AppCompatActivity {
MediaPlayer mp;
public void play(View view) {
mp.start();
}
public void pause(View view) {
mp.pause();
}
public void stop(View view) {
// this seeks to the beginning of the file
mp.seekTo(0);
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mp = MediaPlayer.create(this, R.raw.sample_audio);
}
}

Categories

Resources