将歌曲插入播放列表会返回null

时间:2014-01-06 03:23:35

标签: java android playlist mediastore

我正在尝试构建一个音乐播放器应用程序,我想添加一个功能,以便将歌曲添加到播放列表。这是代码:

public static void addToPlaylist(ContentResolver resolver,SongDetails songDetails,int  playlistId) {
    String[] cols = new String[] {
            "count(*)"
    };
    Uri uri = MediaStore.Audio.Playlists.Members.getContentUri("external", playlistId);
    Cursor cur = resolver.query(uri, cols, null, null, null);
    cur.moveToFirst();
    final int base = cur.getInt(0);
    cur.close();
    ContentValues values = new ContentValues();

    values.put(MediaStore.Audio.Playlists.Members.PLAY_ORDER, Integer.valueOf(base +   songDetails.getId()));
    values.put(MediaStore.Audio.Playlists.Members.AUDIO_ID, songDetails.getId());
    values.put(MediaStore.Audio.Playlists.Members.DISPLAY_NAME, songDetails.getSongTitle());
    values.put(MediaStore.Audio.Playlists.Members.ARTIST, songDetails.getArtistName());
    values.put(MediaStore.Audio.Playlists.Members.DATA, songDetails.getSongData());

    Log.i("URI:",resolver.insert(uri, values)+"");
}

在日志中我总是得到:

URI: null

这意味着歌曲没有添加到播放列表中。是否有人知道为什么没有添加歌曲?

1 个答案:

答案 0 :(得分:4)

我一直在使用这种方法,它对我有用。

 public static String addTracksToPlaylist(final long id, List<MediaData> tracks, final Context context) {
    int count = getPlaylistSize(id, context);
    ContentValues[] values = new ContentValues[tracks.size()];
    for (int i = 0; i < tracks.size(); i++) {
        values[i] = new ContentValues();
        values[i].put(MediaStore.Audio.Playlists.Members.PLAY_ORDER, i + count + 1);
        values[i].put(MediaStore.Audio.Playlists.Members.AUDIO_ID, tracks.get(i).getId());
    }
    Uri uri = MediaStore.Audio.Playlists.Members.getContentUri("external", id);
    ContentResolver resolver = context.getContentResolver();
    int num = resolver.bulkInsert(uri, values);
    resolver.notifyChange(Uri.parse("content://media"), null);
    return String.format(context.getString(R.string.ADDED_TO_PLAYLIST), num, context.getString(R.string.CURRENT));
 }

从播放列表中检索曲目:

public static Cursor getTrackListFromPlaylist(Context context, long plid) {
        String[] MEDIA_COLUMNS = new String[] {
                MediaStore.Audio.Media.ARTIST,
                MediaStore.Audio.Media.ARTIST_ID,
                MediaStore.Audio.Media.TITLE,
                MediaStore.Audio.Playlists.Members.AUDIO_ID,
                MediaStore.Audio.Media.DURATION,
                MediaStore.Audio.Media.DATA,
                MINUTES + "||':'||" + SECONDS + " as " + FORMATTED_DURATION,
                MediaStore.Audio.Media.ALBUM_ID,
                MediaStore.Audio.Media.ALBUM,
                MediaStore.Audio.Media._ID
        };
        return query(context, MediaStore.Audio.Playlists.Members.getContentUri("external", plid),
                MEDIA_COLUMNS, null, null, MediaStore.Audio.Playlists.Members.DEFAULT_SORT_ORDER);
    }