媒体播放器始终循环,永不停止

时间:2016-08-08 04:48:24

标签: android android-mediaplayer

我在once发生Enter关键事件时尝试播放音频EditText

但媒体播放器会播放looping音频和never stop。并且Media Player没有调用setOnCompletionListener方法。

editText.setOnKeyListener(new View.OnKeyListener() {
            @Override
            public boolean onKey(View v, int keyCode, KeyEvent event) {
                if ((event.getAction() == KeyEvent.ACTION_DOWN) &&
                        (keyCode == KeyEvent.KEYCODE_ENTER)) {
                        //Toast.makeText(LoginActivity.this, editText.getText(), Toast.LENGTH_SHORT).show();
                    try {
                        MediaPlayer mp = new MediaPlayer();
                        AssetFileDescriptor afd = getAssets().openFd("oxygen.ogg");
                        mp.setDataSource(afd.getFileDescriptor(),afd.getStartOffset(),afd.getLength());
                        mp.setLooping(false);
                        mp.prepare();
                        mp.start();
                        mp.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
                            @Override
                            public void onCompletion(MediaPlayer mp) {
                                Log.i("ONComplete Media palyer", "onComplete hit");
                                mp.stop();
                                mp.release();
                            }
                        });

                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                    return true;
                }
                return false;
            }
        });

2 个答案:

答案 0 :(得分:1)

我使用setOnSeekCompleteListener方法代替setOnCompletionListener。它现在播放一次并完全停止。

答案 1 :(得分:0)

prepareAsync()setOnPreparedListener()一起使用,当媒体准备好后再播放。

 try {
            MediaPlayer mp = new MediaPlayer();
            AssetFileDescriptor afd = getAssets().openFd("oxygen.ogg");
            mp.setDataSource(afd.getFileDescriptor(), afd.getStartOffset(), afd.getLength());
            mp.setLooping(false);
            mp.prepareAsync();
            mp.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
                @Override
                public void onPrepared(MediaPlayer mp) {
                    mp.start();
                }
            });
            mp.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
                @Override
                public void onCompletion(MediaPlayer mp) {
                    Log.i("ONComplete Media palyer", "onComplete hit");
                    mp.stop();
                    mp.release();
                }
            });
        } catch (Exception e) {
        }