Eyad Lotfy
Eyad Lotfy

Reputation: 67

How to force all sounds to shut down

I'm making an application that makes a sound when a particulate thing happens, I made an other Layout that contains a button to stop that sound but the problem is that whenever I say MediaPlayer.stop();the application on the emulator or even on my mobile says

the application has stopped

The MediaPlayer were imported from the original class,so what I'm thinking about is making a function that shuts all the sounds whether from my app or from outside of my app,any suggestion will be appreciated ;)

here is my code from the original class(which plays the sound)

public void alarm(){
    alarm = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_ALARM);
    alarm_player = MediaPlayer.create(this, alarm);
   if (Alarm_is_on == false){
        alarm_player.setLooping(true);
        alarm_player.start();
       startActivity(new Intent(MainActivity.this, Cancel_alarm.class));
       Alarm_is_on = true;

   }


}

and this is the code from the class // where I stop/pause the sound

public void onClick(View button){

    MainActivity access = new MainActivity();
    access.alarm_player.pause();

}

Upvotes: 2

Views: 158

Answers (2)

Saket Mittal
Saket Mittal

Reputation: 3906

you want to set both ringer & media to zero.So You need to use the AudioManager class

Using AudioManager you can control the volume of media player.

AudioManager audioManager = (AudioManager)getSystemService(Context.AUDIO_SERVICE);
audioManager.setStreamVolume(AudioManager.STREAM_MUSIC, 0, 0);

also for MediaPlayer

public void  setVolume  (float leftVolume, float rightVolume)

for more details - http://developer.android.com/reference/android/media/AudioManager.html

Upvotes: 1

narancs
narancs

Reputation: 5294

First please remove new MainActivity :) If you would like to start a new Activity, use Intents. http://developer.android.com/training/basics/firstapp/starting-activity.html

Second, I would create a separated service (started from a new thead) which is responsible for music player. You can communicate with this Service (NOT IntentService) with Broadcast or with Bind-ing it. In you case I think broadcast are better ways.

Here is a link with a similar project: Android background music service

Good example: http://www.androidhive.info/2012/03/android-building-audio-player-tutorial/

I would like to kindly recommend to read it please, very very useful and can save you life: https://developer.android.com/training/run-background-service/create-service.html

Upvotes: 1

Related Questions