1、引入头文件
#import <AudioToolbox/AudioToolbox.h>
#import <AVFoundation/AVFoundation.h>
2、声明属性
@property (nonatomic, strong) AVAudioPlayer *player; // 音频播放器
@property (nonatomic, strong) NSString *path; // 音频路径
3、初始化
- (AVAudioPlayer *)player {
if (_player == nil) {
AVAudioSession *session = [AVAudioSession sharedInstance];
[session setCategory:AVAudioSessionCategoryPlayback error:nil];
NSURL *url = [[NSURL alloc] initFileURLWithPath:self.path];
NSError *error = nil;
_player = [[AVAudioPlayer alloc] initWithContentsOfURL:url error:&error];
if (error) {
return nil;
}
_player.numberOfLoops = 0; // 设置为0不循环
_player.delegate = self;
}
return _player;
}
遵守协议AVAudioPlayerDelegate
#pragma mark - <AVAudioPlayerDelegate>
- (void)audioPlayerDidFinishPlaying:(AVAudioPlayer *)player successfully:(BOOL)flag {
}
- (void)audioPlayerDecodeErrorDidOccur:(AVAudioPlayer *)player error:(NSError *)error {
}
4、
// 恢复播放
- (void)resumeAudioPlayer {
if (self.player) {
[self.player play];
}
}
// 暂停播放
- (void)pauseAudioPlayer {
if (self.player) {
[self.player pause];
}
}
// 停止播放
- (void)stopAudioPlayer {
if (self.player) {
[self.player stop];
self.player = nil;
}
}