2016-08-08 52 views
1

我試圖播放音頻onceEnter關鍵事件發生在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; 
      } 
     }); 

回答

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) { 
     } 
1

我用setOnSeekCompleteListener方法,而不是setOnCompletionListener。它只播放一次,現在完成。