Search code examples
iosobjective-cavaudioplayer

AVAudioPlayer won't play an mp3 file


When I run app, I hear nothing when app plays my MP3 file: "d.mp3". This file plays okay in iTunes.

I added AVFoundation.framework to project. Added file "d.mp3" to project.

Added to view controller:

#import <UIKit/UIKit.h>
#import "AVFoundation/AVAudioPlayer.h"

- (void)viewDidLoad
{
    [super viewDidLoad];
    // Do any additional setup after loading the view, typically from a nib.

    // Play an MP3 file:
    printf("\n Play an MP3 file");
    NSURL *url = [NSURL fileURLWithPath:[[NSBundle mainBundle]
                                         pathForResource:@"d"
                                         ofType:@"mp3"]];
    printf("\n url = %x", (int)url );
    AVAudioPlayer *audioPlayer = [[AVAudioPlayer alloc]
                                  initWithContentsOfURL:url
                                  error:nil];
    printf("\n audioPlayer = %x", (int)audioPlayer );
    [audioPlayer play];
}

OUTPUT LOG:

Play an MP3 file
url = 3ee78eb0
audioPlayer = 3ee77810

Solution

  • Non-ARC

    You have to retain it during playback because it does not retain itself. It will stop playing instantly once it is dealloc-ed.

    ARC

    You need to hold the AVAudioPlayer instance in the class. And release it after it stops playing. For example,

    #import <AVFoundation/AVFoundation.h>
    
    @interface YourController () <AVAudioPlayerDelegate> {
    AVAudioPlayer *_yourPlayer;   // strong reference
    }
    @end
    
    @implementation YourController
    
    - (IBAction)playAudio:(id)sender
    {
      NSURL *url = [[NSBundle mainBundle] URLForResource:@"d" withExtension:@"mp3"];
      _yourPlayer = [[AVAudioPlayer alloc] initWithContentsOfURL:url error:NULL];
      _yourPlayer.delegate = self;
      [_yourPlayer play];
    }
    
    - (void)audioPlayerDidFinishPlaying:(AVAudioPlayer *)player successfully:(BOOL)flag
    {
        if (player == _yourPlayer) {
           _yourPlayer = nil;
       }
    }
    
    @end
    

    Hope this helps