简体   繁体   中英

Android Mediaplayer Error (-19, 0)

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?

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();

        };
    });

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();
            }
        });

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM