如何将几个文件添加到播放列表

How add a few files into playlist

我使用下一种方法创建新的播放列表:

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);

我有 mp3 文件列表 (ArrayList<File>)。

如何将这些文件添加到新的播放列表中?

在我的例子中,我只有文件列表,所以首先我需要使用文件路径获取音频 ID:

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;

之后我可以将音频添加到播放列表:

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);