我正在尝试使用Android Studio中的内置mediaplayer播放音频文件。我正在使用下面的代码调用意图,并打开第三方文件管理器来获取文件Uri,并从该文件路径中获取我存储在某处的文件路径。无论如何,如果我使用文件管理器(如ES File Explorer),则得到的路径看起来像“/ sdcard / some directory / test.mp3”,但是,如果我使用内置文件浏览器,则得到的路径是“/ documents / audio”。 :1159“用于相同的文件。我知道后者是一个“ Assets ”,但是当我尝试将其输入到媒体播放器中时,会出现异常。我究竟做错了什么?
下面的代码显示了我用来获取文件路径的intent方法,下面的代码显示了我如何使用该文件路径获取Uri并将其输入到mediaplayer中。只是为了清楚起见,“/ sdcard / some directory / test.mp3”之类的文件路径可以正常工作。诸如“/ documents / audio:1159”之类的文件路径不存在。
final View.OnClickListener mGlobal_OnClickListener = new View.OnClickListener() {
public void onClick(final View v) {
int resID2 = v.getId();
Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
intent.setType("audio/*");
try {
startActivityForResult(intent,resID2); }
catch (Exception e) {
Toast.makeText(getApplicationContext(), "Please install a file manager",Toast.LENGTH_LONG).show();
}
}
};
public void onActivityResult(int requestCode,int resultCode,Intent result){
if (resultCode == RESULT_OK)
{
Uri data = result.getData();
String thePath = data.getPath();
// Do something with the file path
}
}
用于根据从上面检索的文件路径启动mediaplayer的代码
Uri myUri = Uri.parse(filePath);
mediaPlayer = new MediaPlayer();
mediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
try {
mediaPlayer.setDataSource(getApplicationContext(), myUri);
mediaPlayer.prepare();
mediaPlayer.start();
} catch (IOException e) {}
最佳答案
我想你不能像这样使用Uri
/documents/audio:1159
使用Intent MediaPlayer时
编辑:
尝试使用以下代码从 Assets 文件夹获取文件路径
AssetManager am = getAssets();
InputStream inputStream = am.open(file:///android_asset/myfoldername/myfilename);
File file = createFileFromInputStream(inputStream);
private File createFileFromInputStream(InputStream inputStream) {
try{
File f = new File(my_file_name);
OutputStream outputStream = new FileOutputStream(f);
byte buffer[] = new byte[1024];
int length = 0;
while((length=inputStream.read(buffer)) > 0) {
outputStream.write(buffer,0,length);
}
outputStream.close();
inputStream.close();
return f;
}catch (IOException e) {
//Logging exception
}
return null;
}
关于java - Android Mediaplayer无法使用路径/documents/audio:1159加载Uri,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25722044/