在录制android时获取音频大小?

时间:2014-08-22 11:57:10

标签: android audio-recording

我正在开发一个Android应用程序。我正在使用MediaRecorder类录制音频。我想在录制时检查录制音频的大小,如果大小超过某些MB我想要停止录制,则检查录制音频的大小。我怎样才能做到这一点。任何帮助将不胜感激 。 公共类RecordAudio {

private MediaRecorder mRecorder = null;

public RecordAudio() {
}

//
public void prepareRecording(String fileName) {

    if (mRecorder == null) {
        mRecorder = new MediaRecorder();
    }

    if (mRecorder != null) {
        mRecorder.setAudioSource(MediaRecorder.AudioSource.MIC);
        mRecorder.setOutputFormat(MediaRecorder.OutputFormat.THREE_GPP);
        mRecorder.setOutputFile(app.appExternalDir + "/" + fileName);
        mRecorder.setAudioEncoder(MediaRecorder.AudioEncoder.AMR_NB);
        System.out.println("this is max::::"+mRecorder.getAudioSourceMax());

        try {
            mRecorder.prepare();

        } catch (IOException e) {

        }
    }
}

// This starts the recording of the voice memo
public void startRecording() {
    if (mRecorder != null) {
        mRecorder.start();
    }

}

// This stops the recording and save the data on storage
public void stopRecording() {
    if (mRecorder != null) {
        mRecorder.stop();
        mRecorder.release();
        mRecorder = null;
    }

}

}

2 个答案:

答案 0 :(得分:0)

使用下面的代码来获取录制文件的大小

 try{
                 File file = new File(path_of_your_recorded_file);
                 long length = file.length();
                 length = length/1024;
                 System.out.println("File Path : " + file.getPath() + ", File size : " + length +" KB");
            }catch(Exception e){
                System.out.println("File not found : " + e.getMessage() + e);
            }

然后,一旦你得到长度,你可以根据你的要求chek希望它将解决你的问题

答案 1 :(得分:0)

对于那些现在遇到这个问题的人:

您可以实现一个界面:

public class RecordingService extends Service implements 
  MediaRecorder.OnInfoListener{

  @Override
  public void onInfo(MediaRecorder mr, int what, int extra) {
    Log.d(TAG_FOREGROUND_SERVICE,"inside the onInfo");
    //check whether file size has reached to Max size to stop recording
    if (what == MediaRecorder.MEDIA_RECORDER_INFO_MAX_FILESIZE_REACHED) 
    {
        Log.d(TAG_FOREGROUND_SERVICE,"Media exceeded the size");
    }
  }
}

在MediaRecorder初始化代码中,您可以设置接口回调和大小 例如:

    mRecorder = new MediaRecorder();
    mRecorder.setOnInfoListener(this);
    mRecorder.setAudioSource(MediaRecorder.AudioSource.MIC);
    mRecorder.setMaxFileSize(Audio_MAX_FILE_SIZE);

希望有所帮助