Jayesh
Jayesh

Reputation: 3871

How to play, pause and stop the song in android?

I am making an app for Android and I have made three buttons to play, pause and stop.

My play and pause buttons are set up, so when I click the play button, it will become invisible and the pause button will display, and vice versa.

It works just fine when I click the play button, but after I click on the pause button, it gives me an error.

The code is given below.

 package com.mpIlango;

 import java.io.IOException;
 import java.util.ArrayList;
 import android.app.Activity;
 import android.media.MediaPlayer;
 import android.os.Bundle;
 import android.view.View;
 import android.widget.Button;
 import android.widget.RadioGroup;
 import android.widget.RadioGroup.OnCheckedChangeListener;

public class MpIlangoActivity extends Activity implements OnCheckedChangeListener {
/** Called when the activity is first created. */


MediaPlayer song1,song2,song3;
int whatsong = 0;

private ArrayList<Integer> songIds;

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);

    RadioGroup rgMusic = (RadioGroup) findViewById(R.id.rgMusic);

    songIds = new ArrayList<Integer>();

    songIds.add(R.raw.fluet);
    songIds.add(R.raw.airtel);
    songIds.add(R.raw.titanic);


    final Button bPlay = (Button) findViewById(R.id.bPlay);
    final Button bStop = (Button) findViewById(R.id.bStop);
    final Button bPause = (Button) findViewById(R.id.bPause);

    bPause.setVisibility(View.GONE);

    rgMusic.setOnCheckedChangeListener(this);

    bPlay.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View v) {           

             if(song1!=null)   {
                   song1.release();
                }

              if(song2!=null)  {
                   song2.release();
                }

              if(song3!=null)  {
                   song3.release();
                }

              switch (whatsong) {

                case 1:

                    try {
                        song1 = MediaPlayer.create(MpIlangoActivity.this, songIds.get(0));
                        song1.prepare();
                    } catch (IllegalStateException e) {                 
                        e.printStackTrace();
                    } catch (IOException e) {                   
                        e.printStackTrace();
                    }
                    song1.start();
                    bPlay.setVisibility(View.GONE);
                    bPause.setVisibility(View.VISIBLE);
                    break;  

                case 2:
                    try {
                        song2 = MediaPlayer.create(MpIlangoActivity.this, songIds.get(1));
                        song2.prepare();
                    } catch (IllegalStateException e) {                 
                        e.printStackTrace();
                    } catch (IOException e) {                   
                        e.printStackTrace();
                    }
                    song2.start();
                    bPlay.setVisibility(View.GONE);
                    bPause.setVisibility(View.VISIBLE);
                    break;

                case 3:
                    try {
                        song3 = MediaPlayer.create(MpIlangoActivity.this, songIds.get(2));
                        song3.prepare();
                    } catch (IllegalStateException e) {                     
                        e.printStackTrace();
                    } catch (IOException e) {               
                        e.printStackTrace();
                    }
                    song3.start();
                    bPlay.setVisibility(View.GONE);
                    bPause.setVisibility(View.VISIBLE);
                    break;
                }
            }               
    });

    bPause.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View v) {

            bPlay.setVisibility(View.VISIBLE);
            bPause.setVisibility(View.GONE);

            if(song1.isPlaying()){
                song1.pause();          
            }

            if(song2.isPlaying()){
                song2.pause();
            }

            if(song3.isPlaying()){
                song3.pause();
            }               
        }
    });

    bStop.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View v) {

             if(song1!=null){
                   song1.release();
               }

              if(song2!=null){
                   song2.release();
               }

              if(song3!=null){
                   song3.release();
               }                
        }
    });;        
}

@Override
public void onCheckedChanged(RadioGroup group, int rbId) {

    switch (rbId) {

    case R.id.rbMusic1:
        whatsong = 1;           
        break;
    case R.id.rbMusic2:
        whatsong = 2;           
        break;
    case R.id.rbMusic3:
        whatsong = 3;           
        break;

    }       

}

  }

Upvotes: 1

Views: 10342

Answers (3)

Nikunj Patel
Nikunj Patel

Reputation: 22066

for pausing the mediaplayer i used...

Mediaplayer.pause();
length=Mediaplayer.getCurrentPosition();

and for resuming the player from the position wer it stopped lately is by......

Mediaplayer.seekTo(length);
Mediaplayer.start();

Upvotes: 2

DecodeGnome
DecodeGnome

Reputation: 1809

Here is a soundmanager/audiomanager class, hope it helps or points you in the right direction ;)

import java.util.HashMap;
import java.util.Random;

import android.content.Context;
import android.media.AudioManager;
import android.media.MediaPlayer;
import android.media.SoundPool;

public class SoundManager {

public boolean          audio;
public boolean          audioSoundFX;
public boolean          audioMusic;

private SoundPool       mSoundPool;
private HashMap<Integer, Integer>       mSoundPoolMap;
private AudioManager    mAudioManager;
private Context         mContext;
private Random          random = new Random();

private MediaPlayer     menuMusic;
private MediaPlayer     gameMusic;
private int             menuMusicCurrentPos = 0;
private int             gameMusicCurrentPos = 0;

public static final SoundManager INSTANCE = new SoundManager();

private SoundManager() {
}

public void setAudio(boolean audioOn){
    if(audioOn){
        audio = true;
    } 
    if(!audioOn) {
        audio = false;
    }
}

public void setSoundFX(boolean soundFX){
    if(soundFX){
        audioSoundFX = true;
    } 
    if(!soundFX) {
        audioSoundFX = false;
    }
}

public void setMusic(boolean music){
    if(music){
        audioMusic = true;
    } 
    if(!music) {
        audioMusic = false;
    }
}


public void initSounds(Context theContext) {

    if (mSoundPool == null){
        mContext = theContext;
        mSoundPool = new SoundPool(4, AudioManager.STREAM_MUSIC, 0);
        mSoundPoolMap = new HashMap<Integer, Integer>();
        mAudioManager = (AudioManager)mContext.getSystemService(Context.AUDIO_SERVICE);

        mSoundPoolMap.put(1, mSoundPool.load(mContext, R.raw.ufo_laser, 1));
        mSoundPoolMap.put(2, mSoundPool.load(mContext, R.raw.enemy_hunter_one_laser, 1));
        mSoundPoolMap.put(3, mSoundPool.load(mContext, R.raw.enemyhuntertwomissile, 1));
        mSoundPoolMap.put(4, mSoundPool.load(mContext, R.raw.enemy_hunter_three_laser, 1));
        mSoundPoolMap.put(5, mSoundPool.load(mContext, R.raw.enemy_drone, 1));
        mSoundPoolMap.put(6, mSoundPool.load(mContext, R.raw.kamikaze, 1));

        mSoundPoolMap.put(14, mSoundPool.load(mContext, R.raw.exploastroidshard, 1));

        mSoundPoolMap.put(11, mSoundPool.load(mContext, R.raw.health, 1));
        mSoundPoolMap.put(12, mSoundPool.load(mContext, R.raw.energy, 1));
        mSoundPoolMap.put(13, mSoundPool.load(mContext, R.raw.shield, 1));

        mSoundPoolMap.put(15, mSoundPool.load(mContext, R.raw.gameover, 1));
        mSoundPoolMap.put(16, mSoundPool.load(mContext, R.raw.gameoverexplo, 1));

        mSoundPoolMap.put(17, mSoundPool.load(mContext, R.raw.menu_beep, 1));
        mSoundPoolMap.put(20, mSoundPool.load(mContext, R.raw.menu_beep, 1));

        menuMusic = MediaPlayer.create(mContext, R.raw.musicmenu);
    }
}

public void playSound(int index, boolean pitching, int loop){
    if(audioSoundFX == true && audio == true){

        float randomPitch;

        if (pitching){
            randomPitch = (float)(random.nextInt(3) + 9) / 10;
        }else{
            randomPitch = 1;
        }

        float streamVolume = mAudioManager.getStreamVolume(AudioManager.STREAM_MUSIC);
        streamVolume = streamVolume / mAudioManager.getStreamMaxVolume(AudioManager.STREAM_MUSIC);
        mSoundPool.play((Integer) mSoundPoolMap.get(index), streamVolume, streamVolume, 1, loop, randomPitch);
    }
}


public void playMenuMusic(){
    if(audioMusic == true && audio == true){
        if (menuMusic == null){
            if(MediaPlayer.create(mContext, R.raw.musicmenu) != null) {
                menuMusic = MediaPlayer.create(mContext, R.raw.musicmenu);
                if(menuMusicCurrentPos != 0){
                    menuMusic.seekTo(menuMusicCurrentPos);                  
                }
                menuMusic.start();
                menuMusic.setVolume(1f , 1f);
                menuMusic.setLooping(true);
            }
        } 
    }
}


public void releaseMenuMusic(){
    if(menuMusic != null){
        this.menuMusicCurrentPos = menuMusic.getCurrentPosition();
        menuMusic.release();
        menuMusic = null;
    }
}


public void playGameMusic(){
    if(audioMusic == true && audio == true){
        if (gameMusic == null){
            gameMusic = MediaPlayer.create(mContext, R.raw.music_game);
            if(menuMusicCurrentPos != 0){
                gameMusic.seekTo(gameMusicCurrentPos);                  
            }
            gameMusic.start();
            gameMusic.setVolume(1f , 1f);
            gameMusic.setLooping(true);
        } 
    }
}


public void releaseGameMusic(){
    if(gameMusic != null){
        this.gameMusicCurrentPos = gameMusic.getCurrentPosition();
        gameMusic.release();
        gameMusic = null;
    }
}

}

Upvotes: 0

cwin
cwin

Reputation: 966

I guess you get a NullPointerException somewhere here!?

if(song1.isPlaying()){
    song1.pause();          
}

if(song2.isPlaying()){
    song2.pause();
}

if(song3.isPlaying()){
    song3.pause();
}               

it that's the problem you may use your switch in here too.

switch (whatsong) {

    case 1: 
        if(song1.isPlaying()){
            song1.pause();          
        }

or initialize your songs somewhere else to make sure they will never be null

I also recommend using only one MediaPlayer.

MediaPlayer song;

bPlay code:

if(song!=null)   {
   song.release();
}

switch (whatsong) {

    case 1:

        try {
            song = MediaPlayer.create(MpIlangoActivity.this, songIds.get(0));
            song.prepare();
        } catch (IllegalStateException e) {                 
            e.printStackTrace();
        } catch (IOException e) {                   
            e.printStackTrace();
        }

}

song.start();
bPlay.setVisibility(View.GONE);
bPause.setVisibility(View.VISIBLE);

bPause code:

bPlay.setVisibility(View.VISIBLE);
bPause.setVisibility(View.GONE);

if(song != null && song.isPlaying()){
    song.pause();          
}

ALL of this Code is untested!

Upvotes: 1

Related Questions