我想在android中录制语音,我尝试开发一个小应用程序进行测试,所以我运行我的应用程序它告诉我我不能在sdcard上写,所以有我的代码:
public class MainActivity extends Activity {
private static final String LOG_TAG_ENREGISTREUR = null;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button record_btn = (Button)findViewById(R.id.button1);
Button stop_btn = (Button)findViewById(R.id.button2);
File fileRecord = null;
final MediaRecorder media = new MediaRecorder();
String state = android.os.Environment.getExternalStorageState();
if(!state.equals(android.os.Environment.MEDIA_MOUNTED)){
Log.e(LOG_TAG_ENREGISTREUR,"SDcard not found!");
return;
}
File repertoryStockage = Environment.getExternalStorageDirectory();
if(!repertoryStockage.canWrite()){
Log.e(LOG_TAG_ENREGISTREUR,"Impossible , you can't write");
return;
}
try {
fileRecord = File.createTempFile("RecordingAudio", ".mp4",repertoryStockage);
} catch (Exception e) {
Log.e(LOG_TAG_ENREGISTREUR,"Probleme E/S before recording");
return;
}
media.setAudioSource(MediaRecorder.AudioSource.MIC);
media.setOutputFormat(MediaRecorder.OutputFormat.THREE_GPP);
media.setAudioEncoder(MediaRecorder.AudioEncoder.AMR_NB);
media.setOutputFile(fileRecord.getAbsolutePath());
record_btn.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
try {
media.prepare();
} catch (IllegalStateException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
media.start();
}
});
stop_btn.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
media.stop();
media.release();
}
});
}
}
我在Manifest中添加权限:
<uses-permission android:name="android.permission.RECORD_AUDIO"/>
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
另一件事我创建SD卡并将其添加到模拟器中:-sdcard“[sdcard的路径]” 那有什么问题?
答案 0 :(得分:1)
嗯,这段代码对我有用..所以可能是你在模拟器中配置错误的东西。我使用了SDK级别15(4.0.3)。
您可以尝试将try
块替换为显示Impossible, You can't write
的日志:
File repertoryStockage = Environment.getExternalStorageDirectory();
File sample = new File(repertoryStockage,"empty.txt");
try
{
sample.createNewFile();
} catch (IOException e) {
e.printStackTrace();
}
if(!sample.canWrite()){
Log.e(LOG_TAG_ENREGISTREUR,"Impossible , you can't write");
return;
}
sample.delete();
我找到了一些地方,表明您无法检查目录的写入权限。 看到这个答案(代码主要来自那个答案):Checking for write access in a directory before creating files inside it
但正如我在开头所说,代码对我有用,没有任何改变。