Search code examples
androidaudiomp3midi

Is there a way to make midi sounds in my Android app?


I'm trying to make an app that can play different midi files at the same time. The files would not be streaming and I would like to include them in the apk.

A maximum of 12 would be played at the same time... Mp3 or a combination of both would also be a suitable substitute but for now midi would be ideal.

Is this at all possible? Thanks in advance to the stack-overflow geniuses! :)

-EltMrx


Solution

  • One easy way to play a single sound is to use MediaPlayer. Put your sound files in the /res/raw folder, then call the below method using R constants, e.g. playSound(R.raw.sound_file_name) where playSound looks something like this:

    private void playSound(int soundResId) {
            MediaPlayer mp = MediaPlayer.create(context, soundResId);
            if (mp == null) {
                Log.warn("playSound", "Error creating MediaPlayer object to play sound.");
                return;
            }
    
            mp.setOnErrorListener(new MediaPlayer.OnErrorListener() {
                public boolean onError(MediaPlayer mp, int what, int extra) {
                    Log.e("playSound", "Found an error playing media. Error code: " + what);
                    mp.release();
                    return true;
                }
            });
    
            mp.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
                public void onCompletion(MediaPlayer mp) {
                    mp.release();
                }
            });
    
            mp.start();
        }
    

    Now, playing multiple sounds at the same time is a bit more complex, but there is a good solution here.