Playing audio once on Processing Android

Hi guys! I was trying to play an audio file only once, not il loop. I found Cassette as an android audio library, but it contains only file.loop() and file.stop(). I was trying to create a function which can do this, but i didn’t find any file.duration or things like that. Help!

@anony ===
why not using android mediaPlayer, it has a lot of methods for duration and so on…
more details here: https://developer.android.com/reference/android/media/MediaPlayer

Thank you so much for the help! I found my reply after a lot of attempts, but i dit it! Then, the function that I used to play a Sound once in processing android is:


MediaPlayer snd = new MediaPlayer();
AssetFileDescriptor fd;
Context context;
Activity act;

void setup(){
  act = this.getActivity();
  context = act.getApplicationContext();
}

void play(){ // name function is not important
  try {
    fd = context.getAssets().openFd("filename.extension");
    snd.setDataSource(fd.getFileDescriptor(),fd.getStartOffset(), fd.getLength());
    snd.prepare();
    snd.start();
  }
  catch (IllegalArgumentException e) {
    e.printStackTrace();
  }
  catch (IllegalStateException e) {
    e.printStackTrace();
  } 
  catch (IOException e) {
    e.printStackTrace();
  }
}

void draw(){
  // code lines...
  if(mousePressed){
    snd.reset(); // THIS IS THE KEY, YOU MUST CALL THIS FUNCTION TO MAKE IT WORK
    play(); // IMPORTANT
  }
}

If you know a more comfortable way, please tell me!
I hope this can help someone.

1 Like

@anony ===
no better solution; you have only to release your player onPause(); you can also recreate it with onResume() (if it is !null)

1 Like