3

我已经从预装在我的设备上的“音乐”应用程序中创建了一个包含 3 首歌曲的播放列表,并且在我自己的应用程序中,我已经成功查询了 MediaStore.Audio.Playlists.EXTERNAL_CONTENT_URI (在调试中检查了名称以确保它是正确的播放列表)并保存它的 id 以供我需要开始播放歌曲时使用。

后来当我开始播放其中一首歌曲时,播放列表中的歌曲计数是正确的,但它播放的曲目与我放入播放列表中的曲目不同。这是从播放列表中获取曲目的代码块。

注意:这是在 PhoneGap 插件中,因此“this.ctx”是 Activity。我的测试设备是运行 Android 2.2 的 HTC Desire,如果有任何相关性的话。

Cursor cursor = null;
Uri uri = null;

Log.d(TAG, "Selecting random song from playlist");
uri = Playlists.Members.getContentUri("external", this.currentPlaylistId);

if(uri == null) {
    Log.e(TAG, "Encountered null Playlist Uri");
}

cursor = this.ctx.managedQuery(uri, new String[]{Playlists.Members._ID}, null, null, null);

if(cursor != null && cursor.getCount() > 0) {
    this.numSongs = cursor.getCount();
    Log.d(TAG, "numSongs: "+this.numSongs); // Correctly outputs 3

    int randomNum = (int)(Math.random() * this.numSongs);
    if(cursor.moveToPosition(randomNum)) {
        int idColumn = cursor.getColumnIndex(Media._ID); // This doesn't seem to be giving me a track from the playlist
        this.currentSongId = cursor.getLong(idColumn);
        try {
            JSONObject song = this.getSongInfo();
            play(); // This plays whatever song id is in "this.currentSongId"
            result = new PluginResult(Status.OK, song);
        } catch (Exception e) {
            result = new PluginResult(Status.ERROR);
        }
    }
}
4

1 回答 1

2

Playlists.Members._ID是播放列表中的 id,可用于对播放列表进行排序

Playlists.Members.AUDIO_ID是音频文件的 ID。

所以你的代码应该像

cursor = this.ctx.query(uri, new String[]{Playlists.Members.AUDIO_ID}, null, null, null);

if(cursor != null && cursor.getCount() > 0) {
    this.numSongs = cursor.getCount();
    Log.d(TAG, "numSongs: "+this.numSongs); // Correctly outputs 3

    int randomNum = (int)(Math.random() * this.numSongs);
    if(cursor.moveToPosition(randomNum)) {
        int idColumn = cursor.getColumnIndex(Playlists.Members.AUDIO_ID); // This doesn't seem to be giving me a track from the playlist
        // or just cursor.getLong(0) since it's the first and only column you request
        this.currentSongId = cursor.getLong(idColumn);
        try {
            JSONObject song = this.getSongInfo();
            play(); // This plays whatever song id is in "this.currentSongId"
            result = new PluginResult(Status.OK, song);
        } catch (Exception e) {
            result = new PluginResult(Status.ERROR);
        }
    }
}
于 2012-09-10T18:46:37.980 回答