Search code examples
iosobjective-cmp3avfoundation

AVaudioPlayer not working and mp3 located in Compile Bundle


I have mp3 file in Copy Bundle Resources and this my code

NSBundle *mainBundle = [NSBundle mainBundle];
NSString *filePath = [mainBundle pathForResource:@"mymp3" ofType:@"mp3"];
NSData *fileData = [NSData dataWithContentsOfFile:filePath];
NSError *error = nil;
AVAudioPlayer *player = [[AVAudioPlayer alloc] initWithData:fileData error:&error];
[player prepareToPlay];

but it doesn't play what is the problem ?

FYI: AVFoundation.framework is included.

Thanks


Solution

  • Try adding

    [player prepareToPlay];
    [player play]; //missing play action
    

    If that doesn't help try this

    @interface AudioPlayerViewController : UIViewController {
        AVAudioPlayer *audioPlayer;
    }
    

    //in your *.m file

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