Xcode 6 - Press button to play sound

2019-07-18 12:34发布

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.

1条回答
疯言疯语
2楼-- · 2019-07-18 13:04

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];
}
查看更多
登录 后发表回答