-->

Android: playing a song file using default music p

2019-02-19 23:04发布

问题:

Is there a way to play a media with the default media player. I can do with the following code

 Intent intent = new Intent(Intent.ACTION_VIEW);
 MimeTypeMap mime = MimeTypeMap.getSingleton();
 String type = mime.getMimeTypeFromExtension("mp3");
 intent.setDataAndType(Uri.fromFile(new File(songPath.toString())), type);
 startActivity(intent);

But this launches a player with less controls and can't push it to the background. Can I launch the player with the default media player?

Thx! Rahul.

回答1:

Try the below code:::

   Intent intent = new Intent(MediaStore.INTENT_ACTION_MUSIC_PLAYER);  
   File file = new File(songPath.toString());  
   intent.setDataAndType(Uri.fromFile(file), "audio/*");  
   startActivity(intent);

Updated:: Try this also

   Intent intent = new Intent();  
   ComponentName comp = new ComponentName("com.android.music", "com.android.music.MediaPlaybackActivity");
   intent.setComponent(comp);
   intent.setAction(android.content.Intent.ACTION_VIEW);  
   File file = new File(songPath.toString());  
   intent.setDataAndType(Uri.fromFile(file), "audio/*");  
   startActivity(intent);


回答2:

I've been researching this for the last few days as I don't have the stock music player. It seems so tragic that it can't be done easily. After looking through various music app's AndroidManifest.xml for clues I stumbled upon MediaStore.INTENT_ACTION_MEDIA_PLAY_FROM_SEARCH.

Using the below method I'm able to start the Samsung music player in the background as long as the song is in the Android MediaStore. You can specify Artist, Album or Title. This method also works for Google Play Music but unfortunately even the newest version of the stock Android player does not have this intent:

https://github.com/android/platform_packages_apps_music/blob/master/AndroidManifest.xml

private boolean playSong(String search){
    try {
        Intent intent = new Intent();
        intent.setAction(MediaStore.INTENT_ACTION_MEDIA_PLAY_FROM_SEARCH);
        intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        intent.putExtra(SearchManager.QUERY, search);
        startActivity(intent);
        return true;
    } catch (Exception ex){
        ex.printStackTrace();
        // Try other methods here
        return false;
    }
}

It would be nice to find a solution that uses a content URI or URL but this solution works for my application.