0

I need to allow the user to stop the music after a preset time. When user enters a new activity, I start the player with a looped sound. But I want the sound to stop automatically after a while. I use this code onCreate of the activity:

final MediaPlayer mp = MediaPlayer.create(getBaseContext(),R.raw.mysound);
mp.setLooping(true);
mp.start(); 

The music starts and never stops... that is not what I want. How do I stop the music after say... 70 seconds?

Thank you

user1137313
  • 2,390
  • 9
  • 44
  • 91

1 Answers1

0

You would probably want to use a service to both start and stop the player.

Here is a tutorial that might be useful.

You can read more about services here.

Mike
  • 211
  • 3
  • 4
  • MediaPlayer starts the music in the background so I think it is a service. Also the music keeps playing even if I press home button or back. – user1137313 Aug 21 '13 at 08:29
  • Yes, but to be sure your code can stop the player you need a Service. An activity is not expected to be alive after you exit the app, however, a Service will. Of course, you could also stop the player when your activity goes into paused or stopped state. – Mike Aug 21 '13 at 12:32
  • I need to play the music only for a certain amount of seconds after the create of the Activity. I can manage the stopping of the music on activity finish or pause or onClick of a button. This works without problems. I need to stop it after an interval of time. So something like a timer that starts counting when player starts... and onTimer music stops. How can I achieve this? – user1137313 Aug 21 '13 at 20:00
  • In the tutorial I can see how to make a service that fires every 10 seconds. I do not need that. It could be useful maybe to start the music... but how do I stop the music / service? In the tutorial there is no reference to that. After trying the tutorial I ended up with a service that keeps firing. I have no idea on how to stop it. – user1137313 Aug 21 '13 at 20:29
  • I ended up using the Chronometer and onChronometerTick with a counter. Not very elegant but a quick solution and pretty straightforward. If you can detail me how to use the service for what I need I will accept your answer. (btw :) I figured out how to stop the service when I want to) – user1137313 Aug 22 '13 at 08:52