a s*_*ich 4 android assets android-mediaplayer
我目前在android项目的原始文件夹中有一组媒体文件,这些文件快速加载并在使用mediaplayer类调用时播放.我需要添加这些文件的更多变体并将它们分类到文件夹中,但显然原始文件夹不支持文件夹.我是否能够从assets文件夹快速加载这些文件并使用mediaplayer播放它们?如果是这样,怎么样?
我有这个方法,通过扩展名返回资产文件夹内的文件夹中的所有文件:
public static String[] getAllFilesInAssetByExtension(Context context, String path, String extension){
Assert.assertNotNull(context);
try {
String[] files = context.getAssets().list(path);
if(StringHelper.isNullOrEmpty(extension)){
return files;
}
List<String> filesWithExtension = new ArrayList<String>();
for(String file : files){
if(file.endsWith(extension)){
filesWithExtension.add(file);
}
}
return filesWithExtension.toArray(new String[filesWithExtension.size()]);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}
Run Code Online (Sandbox Code Playgroud)
如果你用它来调用它:
getAllFilesInAssetByExtension(yourcontext, "", ".mp3");
Run Code Online (Sandbox Code Playgroud)
这将返回资产文件夹根目录中的所有mp3文件.
如果你用它来调用它:
getAllFilesInAssetByExtension(yourcontext, "somefolder", ".mp3");
Run Code Online (Sandbox Code Playgroud)
这将在"somefolder"中搜索mp3文件
现在您已列出要打开的所有文件,您将需要:
AssetFileDescriptor descriptor = getAssets().openFd("myfile");
Run Code Online (Sandbox Code Playgroud)
要播放文件,请执行以下操作:
MediaPlayer player = new MediaPlayer();
long start = descriptor.getStartOffset();
long end = descriptor.getLength();
player.setDataSource(this.descriptor.getFileDescriptor(), start, end);
player.prepare();
player.setVolume(1.0f, 1.0f);
player.start();
Run Code Online (Sandbox Code Playgroud)
希望这可以帮助
这是一个可以从资产文件夹中播放媒体文件的功能.你可以像smth一样使用它play(this,"sounds/1/sound.mp3");
private void play(Context context, String file) {
try {
AssetFileDescriptor afd = context.getAssets().openFd(file);
meidaPlayer.setDataSource(
afd.getFileDescriptor(),
afd.getStartOffset(),
afd.getLength()
);
afd.close();
meidaPlayer.prepare();
meidaPlayer.start();
} catch (IllegalArgumentException e) {
e.printStackTrace();
} catch (IllegalStateException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
12706 次 |
| 最近记录: |