Search code examples
javaandroidplaylist

How add a few files into playlist


I create new playlist using next approach:

ContentResolver resolver = getContentResolver();
ContentValues value = new ContentValues();
value.put(MediaStore.Audio.Playlists.NAME, "Name PlayList");
value.put(MediaStore.Audio.Playlists.DATE_MODIFIED, System.currentTimeMillis());
resolver.insert(MediaStore.Audio.Playlists.EXTERNAL_CONTENT_URI, value);

I have list (ArrayList<File>) of mp3 files.

How can I add this files into newly PlayList?


Solution

  • In my case I have only list of File, so at first I need to get audio Id using path to file:

    public static long getTrackIdByPath(Context context, String pathToFile){
    long id = - 1;
    String[] projection = {MediaStore.Audio.Media._ID,
                           MediaStore.Audio.Media.DATA};
    String selection = MediaStore.Audio.Media.DATA + " like ?";
    Cursor cursor = context.getContentResolver().query(MediaStore.Audio.Media.EXTERNAL_CONTENT_URI,
            projection, selection,
            new String[] {pathToFile}, null);
    cursor.moveToFirst();
    if(cursor.getCount() > 0)
        id = cursor.getLong(0);
    cursor.close();
    return id;
    

    After that I can add audio to playlist:

    ContentResolver resolver = getContentResolver();
    long trackId = getTrackIdByPath(context, pathToFile);
        Uri uri = MediaStore.Audio.Playlists.Members.getContentUri("external", playListId);
        Cursor cursor = resolver.query(uri, new String[] {"count(*)"}, null, null, null);
        cursor.moveToFirst();
        int last = cursor.getInt(0);
        cursor.close();
        ContentValues value = new ContentValues();
            value.put(MediaStore.Audio.Playlists.Members.PLAY_ORDER, ++last);
            value.put(MediaStore.Audio.Playlists.Members.AUDIO_ID, trackId);
    
        resolver.insert(uri, value);