AVAudioPlayer播放本地音频

#import "ViewController.h"
#import 

@interface ViewController ()
//记录systemSoundID
@property (nonatomic, assign) SystemSoundID systemID;
//记录播放器对象
@property (nonatomic, strong) AVAudioPlayer *audioPlayer;
@end

@implementation ViewController

- (AVAudioPlayer *)audioPlayer {
    if (!_audioPlayer) {
        NSURL *audioFilePath = [[NSBundle mainBundle] URLForResource:@"AllOfMe.mp3" withExtension:nil];
        _audioPlayer = [[AVAudioPlayer alloc] initWithContentsOfURL:audioFilePath error:nil];
    }
    return _audioPlayer;
}

//播放音效(<=30s)
- (IBAction)playShortAudio:(id)sender {
    //真机:如果播放系统提供声音(1000 ~ 2000)/震动(静音状态)
    AudioServicesPlaySystemSound(1600);
    AudioServicesPlaySystemSound(kSystemSoundID_Vibrate);
    //播放本地音效文件(创建systemID+播放)
    NSString *shortAudioPath = [[NSBundle mainBundle] pathForResource:@"audio.wav" ofType:nil];
    NSURL *url = [NSURL fileURLWithPath:shortAudioPath];
    AudioServicesCreateSystemSoundID((__bridge CFURLRef _Nonnull)(url), &_systemID);
    //播放
    AudioServicesPlaySystemSound(_systemID);
    
}
//播放本地音频文件
- (IBAction)playLocalAudioFile:(id)sender {
    if ([self.audioPlayer prepareToPlay]) {
        //可以将音频文件文件的数据读到内存(快)
        [self.audioPlayer play];
    }
}
//暂停
- (IBAction)pauseAudioFile:(id)sender {
    if (self.audioPlayer.playing) {
        //正在播放
        [self.audioPlayer pause];
    }
}
//停止(下次播放,从头开始)
- (IBAction)stopAudioFile:(id)sender {
    //设置当前播放的时间偏移量offset为0
    [self.audioPlayer stop];
    self.audioPlayer.currentTime = 0;
}


@end

你可能感兴趣的:(AVAudioPlayer播放本地音频)