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

How to generate multiple files with a media recorder?

我的一些代码:

    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 是一个字符串。

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

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);

然后从数据库中读取文件名使用此行:

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);