Question

how can i play a song file bundled with the application using MPMusicPlayerController ?

code that i tried,

NSString *url = [[NSBundle mainBundle] pathForResource:@"song1" ofType:@"mp3"];
MPMusicPlayerController *myMusicPlayer=[[MPMusicPlayerController alloc] initWithContentURL:[NSURL fileURLWithPath:url]];
[myMusicPlayer play];
Was it helpful?

Solution

MPMusicPlayer controller is only for playing items from the user's iPod library. The AVAudioPlayer will play encoded files from your app's sandbox, and you should be able to convert this code to use AVAudioPlayer easily enough... looks like it would be:

NSString *url = [[NSBundle mainBundle] pathForResource:@"song1" ofType:@"mp3"]; 
AVAudioPlayer *myMusicPlayer=[[AVAudioPlayer alloc]
        initWithContentsOfURL:[NSURL fileURLWithPath:url]
        error:nil];
[myMusicPlayer play];

OTHER TIPS

Better use AVAudioPlayer for playing mp3 from bundle. Even apple insist this, it is easy to set audio session for AVAudioPlayer.(if you are looking to play audio when iPhone is sleeping) MPMusicPlayerController is usually use to play iPod music. but you can select any as per your requirement.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top