Play sound with Android's media player Processing

323 views Asked by At

So I found this code online but for some reason, it doesn't work. I mean it didn't crash but it just couldn't play the file code:

import android.media.MediaPlayer;
import android.content.res.AssetFileDescriptor;
import android.content.Context;
import android.app.Activity;

/////////////////////////////////////////////////////////

MediaPlayer mp;
Context context; 
Activity act;
AssetFileDescriptor afd;

void setup() {
  act = this.getActivity();
  context = act.getApplicationContext();
  try {
    mp = new MediaPlayer();
    afd = context.getAssets().openFd("calm1.mp3");//which is in the data folder
    mp.setDataSource(afd.getFileDescriptor());
    mp.prepare();
  } 
  catch(IOException e) {
    println("file did not load"+e);
  }
  mp.start();
};

void draw() {
};

and the output is:

file did not load java.io.FileNotFoundException: calm1.mp3

pssst im using processing

1

There are 1 answers

0
ludiccc On

This question is a bit old but it needs an answer (as it appears on the search engines).

The following code works the way you asked for. Is a little bit different than yours, it sets the DataSource directly from the AssetFileDescriptor object:

import android.media.MediaPlayer;
import android.content.res.AssetFileDescriptor;
import android.content.Context;
import android.app.Activity;

void setup() {
    AssetFileDescriptor descriptor = this.getActivity().getAssets().openFd("calm1.mp3");

    mp = new MediaPlayer();
    mp.setDataSource(descriptor.getFileDescriptor(), descriptor.getStartOffset(), descriptor.getLength());
    descriptor.close();
    mp.prepare();
    mp.setVolume(1f, 1f);
    mp.setLooping(true);
    mp.start();
}