user2658537
user2658537

Reputation: 11

Play midi file in an asynctask on Android

Here is how my app works:

After the app received the music it will first save the file into the SD card and then play it. I tried to play the music with an asynctask called by a class (not an activity but a handler). However, the music can be played for only 1-2 seconds. Here is the code for the call back of AsyncTask:

fos = new FileOutputStream(file);
fos.write(receivedMusicPayload);
fos.flush();
fos.close();
PlayMusicManager pmm = new PlayMusicManager(qrC);
pmm.execute();

and here is the playermanager:

public class PlayMusicManager extends AsyncTask<Void, Void, Void> {

private QRConnection qrC;

public PlayMusicManager(QRConnection qrC) {
    this.qrC = qrC;

}

@Override
protected Void doInBackground(Void... params) {

    MediaPlayer mediaPlayer = new MediaPlayer();
    File dir = Environment.getExternalStorageDirectory();
    File file = new File(dir, "music.mid");

    if (file.exists()) // check if file exist
    {
        FileInputStream fis;

        try {
            fis = new FileInputStream(file);
            FileDescriptor fd = fis.getFD();
            mediaPlayer.setDataSource( fd);
            mediaPlayer.prepare();
            mediaPlayer.start();

        } catch (IllegalArgumentException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (IllegalStateException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

    } else {
        qrC.getQrActivity().showResult("No such file");
    }

    return null;
}

@Override
protected void onPostExecute(Void parms) {
    qrC.getQrActivity().showResult("Music Done.");
}

Thanks for your help!

Upvotes: 1

Views: 357

Answers (1)

Pavel Jiri Strnad
Pavel Jiri Strnad

Reputation: 314

You need to wait until the file is played.

Because the MediaPlayer mediaPlayer is created as local variable it will be release at the end of

protected Void doInBackground {

You have two options.

1) Make the mediaPlayer variable of class that live long enough 2) OR, put a loop reading mediaPlayer.status. Something like this:

while (mediaPlayer.status==MediaPlayer.Status.PLAYING)
    sleep(100);

Upvotes: 1

Related Questions