如何在android中从原始文件夹播放mp3/mp4到默认播放器



你好,有人能告诉我如何在android默认浏览器上播放mp3/mp4吗?

我在资源中的原始文件夹中有mp3/mp4文件。

我尝试过以下代码,但被忽略了,无法工作,它将打开默认播放器,但没有播放选定的文件。

String dataResourceDirectory = "raw";
String dataResoruceFilename = "armin";
Uri uri = Uri.parse("android.resource://" + getPackageName() + "/" + dataResourceDirectory + "/" + dataResoruceFilename);
Intent intent = new Intent();
intent.setAction(android.content.Intent.ACTION_VIEW);
File file = new File(uri);
intent.setDataAndType(Uri.fromFile(file), "audio/*");
startActivity(intent);

有人能提出建议吗?

您无法将视频从应用程序的专用包播放到默认视频播放器,因为您的默认视频播放器无法识别此路径。

解决方案1复制sd卡中的文件

File sdCard = Environment.getExternalStorageDirectory();
File dir = new File (sdCard.getAbsolutePath() + "/myfolder");
File video = new File (sdCard.getAbsolutePath() + "/myfolder/video.mp4");
if(!dir.isDirectory()) dir.mkdirs();
if(!video.isFile()){
   InputStream ins = getResources().openRawResource(R.raw.test);
   int size;
   try {
     size = ins.available();
     byte[] buffer = new byte[size];
     ins.read(buffer);
     ins.close();
     FileOutputStream fos = new FileOutputStream(new File(dir,"video.m4v"));
     fos.write(buffer);
     fos.close();
  } catch (IOException e) {
      e.printStackTrace();
  }
}
File myvid = new File(dir, "video.m4v");
Intent intent = new Intent(Intent.ACTION_VIEW);
intent.setDataAndType(Uri.fromFile(myvid), "video/*");
this.startActivity(intent);

解决方案2启动videoview视频播放器

VideoView videoView = (VideoView)findViewById(R.id.myvideoview);
MediaController mediaController = new MediaController(this);
mediaController.setAnchorView(videoView);
videoView.setMediaController(mediaController);
String path = "android.resource://" + getPackageName() + "/" + R.raw.video_name_without_extension;
videoView.setVideoPath(path);
videoView.start();

最新更新