Android: playing a song file using default music player

喜欢而已 提交于 2019-12-19 10:46:13

问题


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);
 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 be pushed to the background. Can I launch the player with the default media player?


回答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.



来源:https://stackoverflow.com/questions/10867957/android-playing-a-song-file-using-default-music-player

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!