iphoneiosmpmusicplayercontrollermpmediaitem

Can MPMusicPlayerController can play music from local resource?


i wanna play music with MPMusicPlayerController.

MPMediaItem * mediaItem = [];
MPMediaItemCollection *songs;
NSArray * array = [NSArray arrayWithObjects:mediaItem, nil];
songs = [MPMediaItemCollection collectionWithItems:array];

[[MPMusicPlayerController iPodMusicPlayer] setQueueWithItemCollection:songs];      

i don't know how to give mediaItem, and i have a mp3 file. Help me. thank you!


Solution

  • No, the MPMusicPlayerController will only play music from the Media Library (That's why its located in the MP/MediaPlayer framework) You'll need to use the AVAudioPlayer or the AVPlayer class. A bit more work implementing that unfortunately.

    Something along the lines of this should get you started:

    NSURL *url = [NSURL fileURLWithPath:[NSString stringWithFormat:@"%@/audiofile.mp3",      [[NSBundle mainBundle] resourcePath]]];
    
    NSError *error;
    audioPlayer = [[AVAudioPlayer alloc] initWithContentsOfURL:url error:&error];
    audioPlayer.numberOfLoops = -1;
    
    if (audioPlayer == nil)
        NSLog([error description]);
    else
        [audioPlayer play];