Search code examples
iosobjective-cavaudioplayer

AVAudioPlayer Not playing Mp3 File I tried But no luck


Hi I am using below code to play my local mp3 file. but no error came. but mp3 is not playing.

AVAudioPlayer  *audioPlayer ;
NSString *sound_file;
if ((sound_file = [[NSBundle mainBundle] pathForResource:@"mpthreetest" ofType:@"mp3"])){

    NSURL *url = [[NSURL alloc] initFileURLWithPath:sound_file];
    audioPlayer = [[AVAudioPlayer alloc] initWithContentsOfURL:url error:NULL];
    audioPlayer.delegate = self;


    [audioPlayer prepareToPlay];
    [audioPlayer play];

}

Solution

  • Check Following steps.

    1. Your AppDelegate.m

      #import <AVFoundation/AVAudioSession.h>`<AVFoundation/AVAudioSession.h>
      
    2. Your application:didFinishLaunchingWithOptions: method

      - (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
      {
          self.window = [[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]];
          self.window.backgroundColor = [UIColor whiteColor];
          [[AVAudioSession sharedInstance] setCategory:AVAudioSessionCategoryPlayback error:nil];
      }
      
    3. In Your ViewController.h

      @property (nonatomic,retain) AVAudioPlayer  *audioPlayer ;
      
    4. In Your ViewController.m

      @synthesize audioPlayer;
      

    Then

    NSString *sound_file;
    if ((sound_file = [[NSBundle mainBundle] pathForResource:@"mpthreetest" ofType:@"mp3"])){
    
        NSURL *url = [[NSURL alloc] initFileURLWithPath:sound_file];
        audioPlayer = [[AVAudioPlayer alloc] initWithContentsOfURL:url error:NULL];
        audioPlayer.delegate = self;
    
        [audioPlayer prepareToPlay];
        [audioPlayer play];    
    }
    

    The mistake you did is that you did not set Property.