iosobjective-cxcode4.6

Objective C - IOS - Xcode 4.6.2 - can't hear sound from mp3 files


I'm following in a tutorial on how to play mp3 sounds when pressing a button.

I created a button (playSound).

I added it to the view controller interface:

- (IBACTION)playSound:(id)sender;

in the implementation I declared the needed header files and I wrote the following:

#import "AudioToolbox/AudioToolbox.h"
#import "AVFoundation/AVfoundation.h"

- (IBAction)playSound:(id)sender {

    //NSLog(@"this button works");
    AVAudioPlayer *audioPlayer;
    NSString *audioPath = [[NSBundle mainBundle] pathForResource:@"audio" ofType:@"mp3"];
    //NSLog(@"%@", audioPath);
    NSURL *audioURL = [NSURL fileURLWithPath:audioPath];
    //NSLog(@"%@", audioURL);
    audioPlayer = [[AVAudioPlayer alloc] initWithContentsOfURL:audioURL error:nil];
    [audioPlayer play];

}

I'm not getting any errors. the NSlogs are logging the URL fine, and now I have no clue where to look further. I also checked if my MP3 sound was maybe damaged, but that was also not the case. all i hear is a little crackling noise for 1 second. then it stops.


Solution

  • You declared a local variable audioPlayer to hold a pointer to the player. As soon as your button handler returns the player is being released before it has a chance to play your sound file. Declare a property and use it instead of the local variable.

    In YourViewController.m file

    @interface YourViewController ()
    @property (nonatomic, strong) AVAudioPlayer *audioPlayer;
    @end
    

    or in YourViewController.h file

    @interface YourViewController : UIViewController
    @property (nonatomic, strong) AVAudioPlayer *audioPlayer;
    @end
    

    Then replace audioPlayer with self.audioPlayer in your code.