我正在开发具有记录功能的android应用。我可以录制音频文件并将其保存到设备的存储中,但是似乎存在问题。当我录制两次时,录制的音频将替换第一个录制的音频。
我希望我的应用程序这样做:
我录制了
归档到存储中;
归档到存储中;
这是我正在使用的代码:
import android.app.Activity;
import android.media.MediaRecorder;
import android.os.Bundle;
import android.os.Environment;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;
import java.io.IOException;
public class RecordModule extends Activity {
Button SpeakBtn, StopBtn;
private MediaRecorder myAudioRecorder;
private String outputFile = null;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.recordmodule);
SpeakBtn = (Button) findViewById(R.id.SpeakBtn);
StopBtn = (Button) findViewById(R.id.StopBtn);
StopBtn.setEnabled(false);
SpeakBtn.setEnabled(true);
outputFile = Environment.getExternalStorageDirectory().getAbsolutePath() + "/recording.3gp";
myAudioRecorder = new MediaRecorder();
myAudioRecorder.setAudioSource(MediaRecorder.AudioSource.MIC);
myAudioRecorder.setOutputFormat(MediaRecorder.OutputFormat.THREE_GPP);
myAudioRecorder.setAudioEncoder(MediaRecorder.OutputFormat.AMR_NB);
myAudioRecorder.setOutputFile(outputFile);
SpeakBtn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
try {
myAudioRecorder.prepare();
myAudioRecorder.start();
}
catch (IllegalStateException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
SpeakBtn.setEnabled(false);
StopBtn.setEnabled(true);
Toast.makeText(getApplicationContext(), "Recording started", Toast.LENGTH_LONG).show();
}
});
StopBtn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
myAudioRecorder.stop();
myAudioRecorder.release();
myAudioRecorder = null;
StopBtn.setEnabled(false);
SpeakBtn.setEnabled(true);
Toast.makeText(getApplicationContext(), "Audio recorded successfully", Toast.LENGTH_LONG).show();
}
});
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_record_module, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
最佳答案
第一个记录被覆盖,因此其他记录需要使用另一个文件名。
我建议您使用输出文件名作为创建记录的时间:
Date createdTime = new Date();
outputFile = Environment.getExternalStorageDirectory().getAbsolutePath() + "/" + createdTime + "_rec.3gp";
关于android - 录制和保存音频文件而无需替换另一个,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35378843/