Rob*_*ers 18

最简单的方法是导入AudioToolbox框架,#import <AudioToolbox/AudioToolbox.h>然后您需要做的就是:

NSString *soundPath = [[NSBundle mainBundle] pathForResource:@"Beep" ofType:@"mp3"];
SystemSoundID soundID;
AudioServicesCreateSystemSoundID((__bridge CFURLRef)[NSURL fileURLWithPath:soundPath], &soundID);
AudioServicesPlaySystemSound(soundID);
Run Code Online (Sandbox Code Playgroud)

这对于像哔哔声这样的非常短的声音来说是最好的,因为你不会像对待那样对声音进行太多控制AVAudioPlayer.


Dai*_*jan 10

使用AVAudio - 更多来使用AudioToolbox进行编码,但它也更灵活(如果将来需要它)

0.

#import <AVFoundation/AVFoundation.h>
Run Code Online (Sandbox Code Playgroud)

1.

//conform to delegate and make a property
@interface ViewController () <AVAudioPlayerDelegate>
@property (nonatomic, strong) AVAudioPlayer *audioplayer; //the player
@end
Run Code Online (Sandbox Code Playgroud)

2.

//have a lazy property for the player! where you also tell it to load the sound
#define YourSound @"sound.caf"
- (AVAudioPlayer *)audioplayer {
    if(!_audioplayer) {
        NSURL *audioURL = [[NSBundle mainBundle] URLForResource:YourSound.stringByDeletingPathExtension withExtension:YourSound.pathExtension];
        NSData *audioData = [NSData dataWithContentsOfURL:audioURL];
        NSError *error = nil;
        // assing the audioplayer to a property so ARC won't release it immediately
        _audioplayer = [[AVAudioPlayer alloc] initWithData:audioData error:&error];
        _audioplayer.delegate = self;
    }
    return _audioplayer;
}
Run Code Online (Sandbox Code Playgroud)

3.

//play
- (void)action {
    [self.audioplayer play];
}
Run Code Online (Sandbox Code Playgroud)