Search code examples
androidaudiomp3processing

Working with MP3 sound in Processing for Android ( need to stop )


I am developing an app for Android devices using Processing 2.0, now I have playMP3(); function but need to stop the sound using stopMP3();. I tried everything but what is the best way to load an mp3 and play/stop using processing?, snd.stop(); within the stopMP3 function does not work...

import android.media.*;
import android.content.res.*;

...

MediaPlayer snd;

...

    void setup()
{
MediaPlayer snd = new MediaPlayer();
}

...

void playMP3()
    { 
try {
    AssetManager assets = this.getAssets();
    AssetFileDescriptor fd = assets.openFd("loop1.mp3");
    snd.setDataSource(fd.getFileDescriptor(), fd.getStartOffset(), fd.getLength());
    snd.prepare();
    snd.start();
  snd.setLooping(true);
  }
  catch (IllegalArgumentException e) {
    e.printStackTrace();
  }
  catch (IllegalStateException e) {
    e.printStackTrace();
  } catch (IOException e) {
    e.printStackTrace();
  }

}

void stopMP3(){
????
}

Solution

  • this is a simple sample for media player

    private MediaPlayer   m_Player;
    
    //Start Play Function
    private void startPlaying() {
        m_Player = new MediaPlayer();
        m_Player.setOnCompletionListener(onComplete);
        try {
            if(m_Player.isPlaying())
                stopPlaying();
    
            m_Player.setDataSource(m_FileName);
            m_Player.prepare();
            m_Player.start();
    
        } catch (IOException e) {
    
        }
    }
    
    //Stop Play Function
    private void stopPlaying() {
        m_Player.stop();
        m_Player.reset();
        m_Player = null;
    }
    
    //and this is onComplete Listener
    MediaPlayer.OnCompletionListener onComplete = new OnCompletionListener()
    {
    
        @Override
        public void onCompletion(MediaPlayer mp)
        {
            stopPlaying();
        }
    };
    

    i hope it's helping you