1

I need to get the full length of an album that is on a device but don't get the correct result. What I have is the follwing to get an Array with the songs of one album:

MPMediaPropertyPredicate *albumNamePredicate = [MPMediaPropertyPredicate predicateWithValue:albumTitle
                                 forProperty: MPMediaItemPropertyAlbumTitle];
MPMediaQuery *myAlbumQuery = [[MPMediaQuery alloc] init];
[myAlbumQuery addFilterPredicate: albumNamePredicate];
songsAlbumList = [myAlbumQuery items];

To get the length of a song, I use this:

NSNumber *songTrackLength = [song valueForProperty:MPMediaItemPropertyPlaybackDuration];
int minutes = floor([songTrackLength floatValue] / 60);
int seconds = trunc([songTrackLength floatValue] - minutes * 60);
TracklengthLabel.text = [NSString stringWithFormat:@"%d:%02d", minutes, seconds];

So the above works fine, I just do not get a correct addition of the songdurations ... Any ideas?

4

1 回答 1

0

所以我解决了它 - 我的问题是我不知道如何正确地使用 NSNumbers 进行数学运算 - 我不知道我正在寻找它,这就是我没有要求它的原因。这是我想出的用于计算您设备上专辑长度的代码:

- (void)fullAlbumLength
{
    for (int i=0; i < songsAlbumList.count; i++)
    {
        if (addLength == NULL)  // addLength and addLengthNew are NSNumber variables 
        {
            addLength = [[self.albumTracksList objectAtIndex:i] valueForProperty: @"playbackDuration"];
        }
        else
        {
            addLengthNew = [[self.albumTracksList objectAtIndex:i] valueForProperty: @"playbackDuration"];
            addLength = [NSNumber numberWithFloat:([addLength floatValue] + [addLengthNew floatValue])];
        }
    }
    fullminutes = floor([addLength floatValue] / 60); // fullminutes is an int
    fullseconds = trunc([addLength floatValue] - fullminutes * 60);  // fullseconds is an int
    fullLength.text = [NSString stringWithFormat:@"%02d:%02d", fullminutes, fullseconds];
}

希望这对其他人有帮助。

于 2013-11-09T21:36:50.743 回答