2013-03-03 74 views
1

我有一個像應用程序的音板。即使用戶點擊另一個聲音,我也不希望聲音停止。但是,過了一段時間,像30次點擊(聲音播放器),它停止。我認爲它耗盡內存,或者Android不會讓它超過30個實例。如何在播放完聲音後釋放MediaPlayer?

如何更好地實現這一點,以便在聲音播放完成後,媒體播放器實例被銷燬?

import java.io.IOException; 

public class AudioRecordTest { 
    private static final String LOG_TAG = "AudioRecordTest"; 
    private static String mFileName = null; 
    private MediaRecorder mRecorder = null; 
    private MediaPlayer mPlayer = null; 


    public void startPlaying(int fileName) { 
     mPlayer = new MediaPlayer(); 
     try { 
      mPlayer.setDataSource(mFileName + fileName + ".3gp"); 
      mPlayer.prepare(); 
      mPlayer.start(); 

     } catch (Exception e) { 
      e.printStackTrace(); 
     } 
    } 

    public void stopPlaying() { 
     try { 
      if (mPlayer != null) { 
       mPlayer.release(); 
       mPlayer = null; 
      } 
     } catch (Exception e) { 
      e.printStackTrace(); 
     } 

    } 

    public MediaPlayer getPlayer() { 
     return mPlayer; 
    } 

    public void startRecording(int fileName) { 
     mRecorder = new MediaRecorder(); 
     mRecorder.setAudioSource(MediaRecorder.AudioSource.MIC); 
     mRecorder.setOutputFormat(MediaRecorder.OutputFormat.THREE_GPP); 
     mRecorder.setOutputFile(mFileName + fileName + ".3gp"); 
     mRecorder.setAudioEncoder(MediaRecorder.AudioEncoder.AMR_NB); 

     try { 
      mRecorder.prepare(); 
     } catch (IOException e) { 
      Log.e(LOG_TAG, "prepare() failed"); 
      e.printStackTrace(); 
     } 

     try { 
      mRecorder.start(); 
     } catch (Exception e) { 
      e.printStackTrace(); 
     } 
    } 

    public void stopRecording() { 
     try { 
      if (mRecorder != null) { 
       mRecorder.stop(); 
       mRecorder.release(); 
       mRecorder = null; 
      } 
     } catch (Exception e) { 
      e.printStackTrace(); 
     } 

    } 

    public AudioRecordTest() { 
     mFileName = Environment.getExternalStorageDirectory().getAbsolutePath(); 
     mFileName += "/aaa"; 

    } 

} 

回答

7

試試這個

voicePlayer.getMediaPlayer().setOnCompletionListener(new MediaPlayer.OnCompletionListener() { 
     @Override 
     public void onCompletion(MediaPlayer mediaPlayer) { 
      mediaPlayer.stop(); 
      if (mediaPlayer != null) { 
       mediaPlayer.killMediaPlayer(); 
      } 

     } 
    }); 
+1

.killMediaPlayer()是什麼?你的意思是。發佈?爲什麼在檢查null之前.stop()? – PhilLab 2017-06-12 09:38:50

0

您可以使用release()medeiaplayer的

if(!mediaPlayerObject.isPlaying()) 
    mediaPlayerObject.release(); 
+0

,但將被跳過,同時播放聲音時 – code511788465541441 2013-03-03 18:17:19

+0

設置一個onCompletionListener並做到這一點其所謂的時。然後你可以釋放它。當然,重複使用同一個玩家並且不要創建超過1個會更有意義。 – 2013-03-03 18:24:57

+0

@GabeSechan謝謝你的評論。你說得對。 – 2013-03-03 18:35:25