Android: playing a song file using default music player

前端 未结 2 1448
攒了一身酷
攒了一身酷 2021-01-15 14:39

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

 Intent intent = new Intent(Intent.ACTION_VIEW);
 MimeType         


        
相关标签:
2条回答
  • 2021-01-15 15:01

    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);
    
    0 讨论(0)
  • 2021-01-15 15:12

    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.

    0 讨论(0)
提交回复
热议问题