2015-06-10 88 views
0

我需要從Android設備錄製音頻。開始錄製工作正常,但我無法停止錄音。我得到一個空指針異常錯誤。我正在從其他類訪問start()stop()方法。當我使用stop方法時,記錄爲空。音頻錄製停止時的空指針異常

這裏是我的音樂類

private String getFilename(){ 
     String filepath = Environment.getExternalStorageDirectory().getPath(); 
     File file = new File(filepath,AUDIO_RECORDER_FOLDER); 

     if(!file.exists()){ 
       file.mkdirs(); 
     } 

     return (file.getAbsolutePath() + "/Questionnair_" + System.currentTimeMillis() + file_exts[currentFormat]); 
} 
     public String startRecording(){ 

       recorder = new MediaRecorder(); 
       recorder.setAudioSource(MediaRecorder.AudioSource.MIC); 
       recorder.setOutputFormat(MediaRecorder.OutputFormat.RAW_AMR); 
       recorder.setAudioEncoder(MediaRecorder.AudioEncoder.AMR_NB); 


       recorder.setOutputFile(getFilename()); 
       recorder.setOnErrorListener(errorListener); 
       recorder.setOnInfoListener(infoListener); 



     try { 
       recorder.prepare(); 
       recorder.start(); 
       //dbstore(getFilename()); 






     } catch (IllegalStateException e) { 
       e.printStackTrace(); 
     } catch (IOException e) { 
       e.printStackTrace(); 
     } 



} 
    private MediaRecorder.OnErrorListener errorListener = new  MediaRecorder.OnErrorListener() { 
      @Override 
      public void onError(MediaRecorder mr, int what, int extra) { 
       AppLog.logString("Error: " + what + ", " + extra); 
     } 
}; 


public static Context getAppContext() 
{ 
return Audio.context; 
} 
private MediaRecorder.OnInfoListener infoListener = new MediaRecorder.OnInfoListener() { 
     @Override 
     public void onInfo(MediaRecorder mr, int what, int extra) { 
       AppLog.logString("Warning: " + what + ", " + extra); 
     } 
}; 




     public void stopRecording(View v) { 
      // TODO Auto-generated method stub 
      System.out.println("stoping"); 


       try { 

        if (null != recorder) { 
         System.out.println("recrder is null"); 

        recorder.stop(); 
        recorder.release(); 
        recorder = null; 

        } 

       } catch (IllegalStateException e) { 
        // it is called before start() 


        e.printStackTrace(); 
       } catch (RuntimeException e) { 
        // no valid audio/video data has been received 
        e.printStackTrace(); 
       } 
     } 

這裏是我的代碼怎麼了訪問方法

new Audio().startRecording(); 
new Audio().stopRecording();  

如何解決此問題的停止錄音

+0

你能否請你展示更多的代碼 – Abhishek

+0

有完整的音頻類和方法調用代碼。你想要什麼更多? –

+0

stopRecording方法之間尋找麻煩,你打電話什麼,你已經實現[視圖參數]請檢查。順便說一下,不要使用你的音頻類的新實例調用stopRecording,使用你正在調用啓動方法的同一個實例 – Abhishek

回答

1

你應該這樣做:

private Audio mAudio; 

@Override 
protected void onCreate(Bundle savedInstanceState) { 
    super.onCreate(savedInstanceState); 
    setContentView(R.layout.activity_main); 

    mAudio = new Audio(); 
    mAudio.startRecording();    

} 

public void stopRecording(){ 

    if(mAudio != null){ 

     mAudio.stopRecording(); 

    } 

}