Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
403 views
in Technique[技术] by (71.8m points)

android - How to play audio file from raw/assets folder on the native/default media player?

I know i can play an mp3 file in the media player like that:

Intent intent = new Intent();  
intent.setAction(android.content.Intent.ACTION_VIEW);  
File file = new File(YOUR_SONG_URI);  
intent.setDataAndType(Uri.fromFile(file), "audio/*");  
startActivity(intent);

Following this link I tried to get the URI like:

Uri audio = Uri.parse("android.resource://com.audio.test/"+R.raw.audio1);
Log.d(TAG,"uri:"+audio.toString());

and

Uri audio = Uri.parse("android.resource://com.audio.test/raw/audio");
Log.d(TAG,"uri:"+audio.toString());

Which outputs the expected result:

01-24 15:28:23.190: D/MyClass(30234): uri:android.resource://com.audio.test/2131034112
01-24 15:29:13.: D/MyClass(30234): uri:android.resource://com.audio.test/raw/audio1

But it doesn't work. The media player does not start. Any ideas why?

Update

I included a createChooser and instead of the expected list with players i get a "Unable to find application to perform this action" message. This is my exact code:

 public void playAudio(){
          Intent viewMediaIntent = new Intent();   
          viewMediaIntent.setAction(android.content.Intent.ACTION_VIEW);        
          Uri audio = Uri.parse("android.resource://com.audio.test/raw/"+R.raw.audio1);       
          Log.d(TAG,"uri:"+audio.toString());
          viewMediaIntent.setDataAndType(audio, "video/*");   
          viewMediaIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_SINGLE_TOP);
          Log.d(TAG,"Starting");
          Intent i = Intent.createChooser(viewMediaIntent, "Play Music");
            mGap.startActivity(i);
          Log.d(TAG,"Started");
      }

Update 2

Thank you @CommonsWare for the explanation. Now I understand why it doesn't work. But the problem remains, can I achieve what I want? Get a Uri of a file stored in the raw/assets folder with a file:// scheme?

Update 3

I found a way to do it, although it's not the best it works. I have only 3 files and this doesn't delay the execution at all. I am copying the file from the res/raw to a local directory on the phone and getting the Uri from that file. Any suggestions on how to avoid that step are appreciated.

 public void copyFileToDir(String audioFile){
          File test = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_MUSIC + "/" + audioFile + ".mp3");
          if (test.exists()){
              Toast.makeText(mGap, "Exists", Toast.LENGTH_SHORT).show();
              return;
          }
          File dest = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_MUSIC);
          int i = mGap.getResources().getIdentifier("raw/"+audioFile, "string", mGap.getPackageName());
          InputStream in = mGap.getResources().openRawResource(i);
          // Used the File-constructor
          OutputStream out;
        try {
            out = new FileOutputStream(new File(dest, audioFile + ".mp3"));
              // Transfer bytes from in to out
              byte[] buf = new byte[1024];
              int len;
              try {
                  // A little more explicit
                  while ( (len = in.read(buf, 0, buf.length)) != -1){
                       out.write(buf, 0, len);
                  }
              } finally {
                  // Ensure the Streams are closed:
                  in.close();
                  out.close();
              }
        } catch (FileNotFoundException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } 


      }


      public void playAudio(String audioFile){
          copyFileToDir(audioFile);
          File dest = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_MUSIC + "/" + audioFile + ".mp3");
          Uri r = Uri.fromFile(dest);         
          Intent viewMediaIntent = new Intent();   
          viewMediaIntent.setAction(android.content.Intent.ACTION_VIEW);                                 
          viewMediaIntent.setDataAndType(r, "audio/*");   
          viewMediaIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_SINGLE_TOP);          
          Intent i = Intent.createChooser(viewMediaIntent, "Play Music");
            mGap.startActivity(i);

      }

      public void playVideo(String movieurl){
          Intent intentToPlayVideo = new Intent(Intent.ACTION_VIEW);
          intentToPlayVideo.setDataAndType(Uri.parse(movieurl), "video/*");
          Log.d(TAG,"Playing:" + movieurl);
          mGap.startActivity(intentToPlayVideo);
      }
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Any reason why don't you use the MediaPlayer directly? You can pass the resource id directly

int resourceId = R.raw.your_media_resource;
MediaPlayer mediaPlayer = MediaPlayer.create( context, resourceId );
mediaPlayer.setOnCompletionListener( new OnCompletionListener()
{
    @Override
    public void onCompletion( MediaPlayer mp )
    {
        mp.release();
    }
} );
mediaPlayer.start();

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...