首页 文章

Android媒体播放器不会使用路径/文档/音频加载Uri:1159

提问于
浏览
0

我正在尝试使用Android Studio中的内置媒体播放器播放音频文件 . 我正在使用下面的代码来调用一个intent并打开第三方文件管理器以获取文件Uri以及我存储在某处的文件路径 . 无论如何,如果我使用像ES文件资源管理器这样的文件管理器,我会得到一个看起来像“/ 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) {}

1 回答

  • 0

    我想你不能用Uri喜欢

    / documents / audio:1159

    何时使用Intent MediaPlayer

    EDITTED:尝试使用此代码从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;
    }
    

相关问题