Sound Player

There are several ways to play audio on Android. One of the basic capabilities is to simply playback audio files that are saved with a Sketch. The below example uses a class called SoundPlayer (code below) to play an audio file (“beep.ogg“) that has been placed into the Sketch’s data folder.

SoundPlayer beepSound;
SoundPlayer otherSound;

void setup() {
  beepSound = new SoundPlayer(this,"beep.ogg");
  //otherSound = new SoundPlayer(this,"other.wav");
}

void draw() {
  
}

void mousePressed() {
  beepSound.play();
}
class SoundPlayer extends Object  implements android.media.MediaPlayer.OnCompletionListener {
  
  android.media.MediaPlayer mediaPlayer;
  android.content.res.AssetFileDescriptor assetFileDescriptor;
  processing.core.PApplet theSketch;
  
  boolean ready = false;
  
  public SoundPlayer(PApplet _theSketch, String audioFile) {
    theSketch = _theSketch;
    
    try {
      assetFileDescriptor = theSketch.getAssets().openFd(audioFile);
      
      mediaPlayer = new android.media.MediaPlayer();
      mediaPlayer.setDataSource(assetFileDescriptor.getFileDescriptor(),assetFileDescriptor.getStartOffset(), assetFileDescriptor.getLength());
      mediaPlayer.setOnCompletionListener(this);
      mediaPlayer.prepare();
      ready = true;
    } catch (Exception e) {
      println(e); 
    }
  }
  
  public void play() {
    if (ready) {
      try {
        mediaPlayer.start();
        ready = false;
        println("playSound");
      } catch (Exception e) {
        println(e); 
      }
    }
  }
  
  public void onCompletion(android.media.MediaPlayer mp) { 
    try {
      println("Trying to prepare");
      mediaPlayer.stop();
      mediaPlayer.prepare();
      ready = true;
    }
    catch (Exception e) {
      println(e); 
    }
  }  
}  

The SoundPlayer class uses the built-in MediaPlayer class which is the base class for video playback as well. We’ll dig deeper into the MediaPlayer in future classes.