Android中的标准方式似乎是将资源存储在res/sound
或类似的东西中。然后Android间接生成一个R.sound.xxx
int,可用于访问该文件。
我想在我的应用程序中批量几百个小的声音文件,并通过SQLlite数据库从音频文件中加载文件名。这意味着我不能依赖R.sound.xxx
int。
我应该在哪里存储我的声音文件以及如何访问它们?
充其量我想使用setDataSource,这样我就可以播放多个文件,而无需为每个文件创建新的媒体播放器。
类似的东西(但“file.mp3”不能用作路径):
public void prepareAudio(MediaPlayer mp, Context context) {
try {
mp.setDataSource("file.mp3");
mp.setAudioStreamType(AudioManager.STREAM_MUSIC);
mp.prepare();
} catch (IllegalStateException e) {
Log.e(TAG, "IllegalStateException for mediaplayer with file " + getAudioFileName(), e);
} catch (IOException e) {
Log.e(TAG, "Can't read audio file " + getAudioFileName(), e);
}
}
当我尝试(文件夹res {raw)中的文件file.mp3
时:
public void prepareAudio(MediaPlayer mp, Context con) {
Log.d(TAG, "Prepare audio start");
try {
int rawresid = con.getResources().getIdentifier("file.mp3",
"raw", con.getPackageName());
AssetFileDescriptor afd = con.getResources().openRawResourceFd(rawresid);
mp.setDataSource(afd.getFileDescriptor(), afd.getStartOffset(), afd.getDeclaredLength());
mp.setAudioStreamType(AudioManager.STREAM_MUSIC);
mp.prepare();
mp.start();
} catch (IllegalStateException e) {
Log.e(TAG, "IllegalStateException for mediaplayer with file " + getAudioFileName(), e);
} catch (IOException e) {
Log.e(TAG, "Can't read audio file " + getAudioFileName(), e);
}
Log.d(TAG, "Prepare audio end");
}
我收到错误:
09-01 18:23:08.590: W/ResourceType(15257): No package identifier when getting value for resource number 0x00000000
09-01 18:23:08.590: D/AndroidRuntime(15257): Shutting down VM
09-01 18:23:08.590: W/dalvikvm(15257): threadid=1: thread exiting with uncaught exception (group=0x41990d40)
09-01 18:23:08.600: E/AndroidRuntime(15257): FATAL EXCEPTION: main
09-01 18:23:08.600: E/AndroidRuntime(15257): Process: com.pairs.pairs, PID: 15257
09-01 18:23:08.600: E/AndroidRuntime(15257): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.pairs.pairs/com.pairs.pairs.TwoChoice}: android.content.res.Resources$NotFoundException: Resource ID #0x0
答案 0 :(得分:1)
您可以使用资源getIdentifier和openRawResource
来访问您的/ res / raw文件夹,访问权限示例:
InputStream ins = getResources().openRawResource(getResources().getIdentifier("FILENAME_WITHOUT_EXTENSION",
"raw", getPackageName()));
编辑:
要使用MediaPlayer,您不必调用openRawResource,只需使用getIdentifier。实施例
MediaPlayer mediaPlayer = MediaPlayer.create(this,getResources().getIdentifier("FILENAME_WITHOUT_EXTENSION",
"raw", getPackageName()));
mediaPlayer.start();
编辑2:
试试这个:
int rawresid = getResources().getIdentifier("FILENAME_WITHOUT_EXTENSION",
"raw", getPackageName());
AssetFileDescriptor afd = getResources().openRawResourceFd(rawresid);
mp.setDataSource(afd.getFileDescriptor(), afd.getStartOffset(), afd.getDeclaredLength());