2

Looking for some help trying to get my button to play sound. I've looked up over 50 tutorials but all of them are outdated and do not work with the new Xcode. Does anyone have a good resource to learn? Fairly new to Objective-C. I've looked through the Apple documentation for the Audio frameworks and my brain cells committed suicide. Any help or pointers in the right direction would be greatly appreciated.

Bryner
  • 397
  • 3
  • 18

1 Answers1

4

in viewController.h

#import <AudioToolbox/AudioToolbox.h>

#import <AVFoundation/AVFoundation.h>

@interface viewController : UIViewController
@property (strong, nonatomic) AVAudioPlayer *player;
@end

and viewController.m

-(void)yourButtonDidTap {
    NSString *soundFilePath = [NSString stringWithFormat:@"%@/%@.mp3",
                               [[NSBundle mainBundle] resourcePath], soundName];
    NSURL *soundFileURL = [NSURL fileURLWithPath:soundFilePath];

    _player = [[AVAudioPlayer alloc] initWithContentsOfURL:soundFileURL
                                                                   error:nil];
    _player.numberOfLoops = 0; 

    [_player play];
}
SeanChense
  • 846
  • 8
  • 14