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?
So I solved it - my problem was that I did not know how to correctly do the math with NSNumbers - I did not know that I was looking for that, that's why I did not ask for it. Here is the code I came up with to calculate the length of an album on you device:
- (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];
}
Hope this is helpful for someone else out there.