Android Mediaplayer Error (-19, 0)

2019-07-20 20:18发布

问题:

I try to replay a sound when I click on a button. But I get the Error (-19, 0) (what ever this means^^)

My code:

final Button xxx = (Button)findViewById(R.id.xxx);

        xxx.setOnClickListener(new View.OnClickListener() {
            public void onClick(View v) {
                MediaPlayer mp = MediaPlayer.create(getApplicationContext(), R.raw.plop); 
                mp.start();
            }
        });

What is my mistake?

回答1:

I was getting the same problem, I solved it by adding the following code:

mp1 = MediaPlayer.create(sound.this, R.raw.pan1);
mp1.start();
    mp1.setOnCompletionListener(new OnCompletionListener() {
        public void onCompletion(MediaPlayer mp) {
        mp.release();

        };
    });


回答2:

You need to release the previous media player before starting the new one.

Declare MediaPlayer as a instance variable and then:

mp = null;
final Button xxx = (Button)findViewById(R.id.xxx);

        xxx.setOnClickListener(new View.OnClickListener() {
            public void onClick(View v) {
                if (mp != null) {
                  mp.stop();
                  mp.release();
                }

                mp = MediaPlayer.create(getApplicationContext(), R.raw.plop); 
                mp.start();
            }
        });

Or in your case, since you always play the same sound you don't need to release the player and create a new one, simply reuse the old one.

final MediaPlayer mp = MediaPlayer.create(getApplicationContext(), R.raw.plop);
mp.prepare(); // Blocking method. Consider to use prepareAsync

final Button xxx = (Button)findViewById(R.id.xxx);

        xxx.setOnClickListener(new View.OnClickListener() {
            public void onClick(View v) {
                mp.stop();
                mp.start();
            }
        });


回答3:

I sloved this problem by this code:

    public static void playSound() {
    mMediaPlayer = new MediaPlayer();
    try {
        AssetFileDescriptor afd = context.getAssets().openFd("type.mp3");
        mMediaPlayer.setDataSource(afd.getFileDescriptor(),
                afd.getStartOffset(), afd.getLength());
        mMediaPlayer.prepare();
        mMediaPlayer.start();
        mMediaPlayer.setOnCompletionListener(new OnCompletionListener() {

            @Override
            public void onCompletion(MediaPlayer arg0) {
                // TODO Auto-generated method stub
                arg0.release();
            }
        });
    } catch (IllegalArgumentException | IllegalStateException | IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
}

i hope to help you.