如何使用媒体记录器生成多个文件?

时间:2017-07-30 16:18:36

标签: android audio-recording mediarecorder

我的一些代码:

    outPutFile = Environment.getExternalStorageDirectory().getAbsolutePath() + "/recording.3gp";

    mediaRecorder = new MediaRecorder();
    mediaRecorder.setAudioSource(MediaRecorder.AudioSource.MIC);
    mediaRecorder.setOutputFormat(MediaRecorder.OutputFormat.THREE_GPP);
    mediaRecorder.setAudioEncoder(MediaRecorder.AudioEncoder.AMR_NB);
    mediaRecorder.setOutputFile(outPutFile);

用于显示文件的列表和适配器

    listRecord.addAll(Arrays.asList(outPutFile));
    listAdapter = new ArrayAdapter<String>(this, R.layout.support_simple_spinner_dropdown_item, listRecord);
    recordList.setAdapter(listAdapter);

outPutFile是一个字符串。

1 个答案:

答案 0 :(得分:1)

每次要记录新文件名时都必须更改文件名,因此可以将日期时间添加到文件名以创建唯一名称:

String dateTime = new SimpleDateFormat("dd-MM-yyyy hh-mm-ss aa",Locale.getDefault()).format(new Date());
outputFile = Environment.getExternalStorageDirectory().getAbsolutePath() + "/Recordings/recording -" + dateTime + ".3gp";

显示您必须创建数据库以保存文件名的项目,并在您想要显示录制列表时从数据库中获取文件名

String DIR_DATABASE = Environment.getExternalStorageDirectory().getAbsolutePath() + "/Recordings";
String sqliteQuery= "CREATE  TABLE  IF NOT EXISTS Recordings (ID INTEGER PRIMARY KEY  AUTOINCREMENT  NOT NULL  UNIQUE , fileName VARCHAR)"
SQLiteDatabase database = SQLiteDatabase.openOrCreateDatabase(DIR_DATABASE + "db.sqlite", null);
database.execSQL(sqliteQuery);

并将数据插入数据库使用:

SQLiteDatabase database = SQLiteDatabase.openDatabase(DIR_DATABASE + "db.sqlite", null, 0);
ContentValues values = new ContentValues();
                values.put("fileName", outputFile );
                database.insert("Recordings", "", values);

然后从数据库读取fileNames使用以下行:

Cursor cursor = database.rawQuery("SELECT fileName FROM Recordings", null);
ArrayList<String> fileNames = new ArrayList<>();
while (cursor.moveToNext()) {

     String fileName = cursor.getString(0);
     fileNames.add(fileName);
}
cursor.close();
database.close();

最后将它们添加到列表适配器:

listRecord.addAll(fileNames);
listAdapter = new ArrayAdapter<String>(this, R.layout.support_simple_spinner_dropdown_item, listRecord);
recordList.setAdapter(listAdapter);