iOS之AVAudioPlayer 音频播放

一,AVAudioPlayer本地音频播放
  • 使用AVAudioPlayer,需要导入AVFoundation.framework;
  • 支持的音频格式包括:AAC、ALAC、IMA4、linear、MP3;
  • AVAudioPlayer支持播放单个声音的能力,但并不支持流式播放,所以必须是缓冲完才能播放;
#import 
@interface AudioToolManager()
/**
 播放器
 */
@property (nonatomic, strong) AVAudioPlayer *player;
@end
@implementation AudioToolManager
//初始化播放器
-(AVAudioPlayer*)player{
    if (!_player) {
        NSError *err;
        NSURL *url = [[NSBundle mainBundle] URLForResource:@“xxx” withExtension:@"mp3"];//wav
        _player = [[AVAudioPlayer alloc] initWithContentsOfURL:url error:&err];
        _player.delegate = self;
        //获取系统的声音
        AVAudioSession *audioSession = [AVAudioSession sharedInstance];
        CGFloat currentVol = audioSession.outputVolume; 
        //设置播放器声音
        _player.volume = currentVol;
        //设置播放速率
        _player.rate = 1.0;
        //设置播放次数,负数代表无限循环
//        _player.numberOfLoops = 1;
        //预加载资源
        [_player prepareToPlay];
    }
    return _player;
}

//开始播放
-(void)startPlay{
    if ([self.player isPlaying]) {
        [self.player stop];
    }
    [self.player play];
}

//停止播放
-(void)stopPlay{
    [self.player stop];
}

//暂停播放
-(void)pausePLay{
   [self.player pause];
}

#pragma mark -- delegate
// 音频播放完成时
- (void)audioPlayerDidFinishPlaying:(AVAudioPlayer *)player successfully:(BOOL)flag{
    NSLog(@“播放完成”);
}

// 音频播放出错时
- (void)audioPlayerDecodeErrorDidOccur:(AVAudioPlayer *)player error:(NSError * __nullable)error{
    NSLog(@“播放出错了”);
}
@end

你可能感兴趣的:(iOS之AVAudioPlayer 音频播放)