我正在尝试实现音频分配器。我的要求是,如果音频持续时间超过30秒,则应将音频分成30秒中的每个音频文件。
为此,我在启动记录器时启动了一个计时器,每30秒停止记录一次,保存文件并重新启动记录器。这可以正常工作,并且音频文件已保存在设备上。但是,当我尝试打开它们时,只有最后一个音频文件播放,所有文件似乎都已损坏。
以下是我的代码:-
/**
* Allow the app to record the audio after the user has granted permission.
*
* @param mContext
*/
public static void allowRecording(final Activity mContext)
{
isRecording = true;
mStartRecording = true;
if (!mRecord)
{
if (timer != null)
{
timer.cancel();
stopRecording();
mRecord = true;
}
}
mRecord = false;
// start record,at every 30 seconds
timer = new Timer();
timer.schedule(new TimerTask()
{
@Override
public void run()
{
i++;
mContext.runOnUiThread(new Runnable()
{
@Override
public void run()
{
onRecord(mStartRecording, i, mContext);
mStartRecording = !mStartRecording; // setting false
}
});
}
}, 0, 30000);
}
/**
* Check if the stop button has been pressed.
* If not stop recording audio automatically after an interval eg .10 secs and start the recording again.
*
* @param start
* @param i
* @param mContext
*/
private static void onRecord(boolean start, int i, Activity mContext)
{
if (isRecording)
{
if (start)
{
startRecording(outputFileDirectory + mContext.getString(R.string.str_audio) + i + mContext.getString(R.string.str_file_type_mp4));
}
else
{
stopRecording();// stop recording
startRecording(outputFileDirectory + mContext.getString(R.string.str_audio) + i + mContext.getString(R.string.str_file_type_mp4));//imeadiatly start recording
}
}
else
{
timer.cancel();
}
}
/**
* Start recording audio
*/
public static void startRecording(String mFileName)
{
if (mediaPlayer != null && mAudioRecorder != null)
{
mediaPlayer.stop();
mAudioRecorder.release();
mediaPlayer = null;
mAudioRecorder = null;
}
mAudioRecorder = new MediaRecorder();
mAudioRecorder.setAudioSource(MediaRecorder.AudioSource.MIC);
mAudioRecorder.setOutputFormat(MediaRecorder.OutputFormat.THREE_GPP);
mAudioRecorder.setAudioEncoder(MediaRecorder.OutputFormat.AMR_NB);
mAudioRecorder.setOutputFile(mFileName);
clippingList.add(mFileName);
try
{
mAudioRecorder.prepare();
mAudioRecorder.start();
}
catch (IOException e)
{
e.printStackTrace();
}
}
/**
* Automatic method to stop recording only to continue the recording again after an interval
*/
private static void stopRecording()
{
if (mAudioRecorder != null)
{
mAudioRecorder.stop();
mAudioRecorder.release();
mAudioRecorder = null;
}
}
public static List<String> stopRecording completely()
{
if (mAudioRecorder != null)
{
mAudioRecorder.stop();
mAudioRecorder.release();
mAudioRecorder = null;
timer.cancel();
}
isRecording = false;
isAudioPlaying = false;
return clippingList;
}
对此有任何帮助。