Search code examples
androidandroid-mediaplayermultiple-instances

android player plays about 30 times and stops


The following plays for about 30 consecutive times, and then stops playing audio. (The program continues to run.) I have read that I may be creating too many instances of the player. How can I modify this code to prevent that? (This code has been edited using suggestions and is still playing only about 30 times.)

public static MediaPlayer m;
private void playboopboop(String fileName) {
    try {
        AssetFileDescriptor d = getAssets().openFd(fileName);
        long start = d.getStartOffset();
        long end = d.getLength();
        this.m = new MediaPlayer();
        this.m.setDataSource(d.getFileDescriptor(), start, end);
        this.m.setLooping(false);
        this.m.prepare();
        this.m.start();
    } catch (Exception e) {
        doalert("Audio Error: " + e);
    }
}

Solution

  • The reset method will stop any media and send the MediaPlayer instance back to the idle state, in the same state when it was created. The working code is as follows:

    public MediaPlayer m = new MediaPlayer();
    private void playboopboop(String fileName) {
        try {
            AssetFileDescriptor d = getAssets().openFd(fileName);
            long start = d.getStartOffset();
            long end = d.getLength();
            m.reset(); // set player to initial creation state
            m.setDataSource(d.getFileDescriptor(), start, end);
            m.prepare();
            m.start();
        } catch (Exception e) {
            doalert("Audio Error: " + e);
        }
    }