Search code examples
iphoneuilocalnotificationmpmediapickercontroller

Access ipod music library and display soundlist with length


I am trying access iPod music library and after that creating a local notification when my application is in background. I want to play the selected sound in local notification. My problem is Apple allow only those files which are less then 30sec. in length.

So is there any way to get list of only those sound which are less then 30sec length?

If I get this list then I need to copy the selected media file in my resource bundle. Then I can paas it to my local notification. until and unless if there is any way to paas a media item directly to local notification.

Thanks to all for helping..


Solution

  • Assuming you want items under "music" only (not podcasts or ringtones), something like this should work:

    MPMediaQuery * query = [MPMediaQuery songsQuery];
    NSArray * items = [query items];
    NSPredicate * predicate = [NSPredicate predicateWithBlock:
       ^(id evaluatedObject, NSDictionary *bindings){
         MPMediaItem * item = evaluatedObject;
         NSNumber * duration = [item valueForProperty:MPMediaItemPropertyPlaybackDuration];
         return [duration doubleValue] < 30;
       }];
    NSArray * filteredItems = [items filteredArrayUsingPredicate:predicate];
    

    Unfortunately MPMediaPropertyPredicate doesn't let us filter by "duration less than 30 seconds" (the comparison types are "EqualTo" and "Contains"), so we do it manually above.

    Then you need to export the desired track using AVAssetExportSession. You probably need to convert it to one of the supported formats in the Local and Push Notification Programming Guide. I also suggest using a fixed filename so it's easier to keep track of the files you've created.

    Finally, you can't write to your app bundle since this invalidates the code signature (apparently you used to be able to; perhaps the signature is only checked at install time). However, you might be able to use a relative path like ../Library/Application Support/MyApp/MySound.mp4.

    Note that this is not guaranteed to work and might fail app review! In particular,

    • There's no guarantee that the path will start with ../Library. An algorithm for generating relative paths is beyond the scope of this answer. (An absolute path probably won't work since it doesn't work with -[NSString stringByAppendingPathComponent:].)
    • There's no guarantee that UILocalNotification.soundName will accept a path; the documentation simply says it accepts a "filename (including extension) of a sound resource in the application’s main bundle".