[英]Android mediaplayer won't load Uri with path /documents/audio:1159
我正在嘗試使用Android Studio中的內置mediaplayer播放音頻文件。 我正在使用下面的代碼調用意圖,並打開第三方文件管理器來獲取文件Uri,並從該文件路徑中獲取我存儲在某處的文件路徑。 無論如何,如果我使用像ES File Explorer這樣的文件管理器,我會得到一個看起來像“ / sdcard / some directory / test.mp3”的路徑,但是,如果我使用內置文件瀏覽器,我會得到一個像“ / documents / audio”的路徑。 :1159“用於相同的文件。 我知道后者是一個“資產”,但是當我嘗試將其輸入到媒體播放器中時,會出現異常。 我究竟做錯了什么?
下面的代碼顯示了我用來獲取文件路徑的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時
編輯:嘗試使用此代碼從資產文件夾獲取文件路徑
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;
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.