123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308 |
- //
- // AudioEnginePlayer.m
- // KulexiuForStudent
- //
- // Created by 王智 on 2024/6/4.
- //
- #import "AudioEnginePlayer.h"
- #import <AVFoundation/AVFoundation.h>
- @interface AudioEnginePlayer ()
- /** 定时器 */
- @property (nonatomic, strong) NSTimer *timer;
- @property (nonatomic, strong) AVAudioEngine *audioEngine;
- @property (nonatomic, strong) AVAudioPlayerNode *bgPlayer;
- @property (nonatomic, strong) AVAudioUnitTimePitch *timePitchUnit;
- @property (nonatomic, strong) AVAudioFile *audioFile;
- @property (nonatomic, strong) AVAudioFormat *audioFormat;
- @property (nonatomic, assign) NSTimeInterval totalDuration;
- @property (nonatomic, assign) AVAudioFramePosition startPosition; // 开始位置
- @end
- @implementation AudioEnginePlayer
- - (instancetype)init {
- self = [super init];
- if (self) {
- }
- return self;
- }
- - (void)setupAudioSession {
- AVAudioSession *audioSession = [AVAudioSession sharedInstance];
-
- @try {
- NSError *err = nil;
- AVAudioSessionCategory category = AVAudioSessionCategoryPlayAndRecord;
- if (@available(iOS 10.0, *)) {
- [audioSession setCategory:category mode:AVAudioSessionModeDefault options:AVAudioSessionCategoryOptionAllowBluetooth|AVAudioSessionCategoryOptionAllowBluetoothA2DP|AVAudioSessionCategoryOptionDefaultToSpeaker|AVAudioSessionCategoryOptionMixWithOthers error:&err];
- }
- else {
- [audioSession setCategory:category withOptions:AVAudioSessionCategoryOptionAllowBluetooth|AVAudioSessionCategoryOptionDefaultToSpeaker|AVAudioSessionCategoryOptionMixWithOthers error:&err];
- }
- [audioSession setActive:YES error:&err];
- } @catch (NSException *exception) {
- NSLog(@"----- exception --- %@", exception);
- } @finally {
- [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(handleInterruption:) name:AVAudioSessionInterruptionNotification object:audioSession];
- }
- }
- // 打断处理
- - (void)handleInterruption:(NSNotification *)notification {
-
- NSDictionary *info = notification.userInfo;
- AVAudioSessionInterruptionType type = [info[AVAudioSessionInterruptionTypeKey] unsignedIntegerValue];
- if (type == AVAudioSessionInterruptionTypeBegan) {
- //Handle InterruptionBegan
- if (self.delegate && [self.delegate respondsToSelector:@selector(enginePlayerDidError:error:)]) {
- NSError *error = [[NSError alloc] initWithDomain:NSCocoaErrorDomain code:99999 userInfo:@{@"errorDesc" : @"播放被打断"}];
- [self.delegate enginePlayerDidError:self error:error];
- }
- }
- else {
- AVAudioSessionInterruptionOptions options = [info[AVAudioSessionInterruptionOptionKey] unsignedIntegerValue];
- if (options == AVAudioSessionInterruptionOptionShouldResume) {
- //Handle Resume
-
- [[AVAudioSession sharedInstance] setActive:YES error:nil];
- // [self startEngine];
- }
- }
- }
- - (void)configEngine {
- [self setupAudioSession];
- self.audioEngine = [[AVAudioEngine alloc] init];
- self.bgPlayer = [[AVAudioPlayerNode alloc] init];
-
- // attach node
- [self.audioEngine attachNode:self.bgPlayer];
- [self.audioEngine attachNode:self.timePitchUnit];
- }
- - (void)loadAudioFile:(NSURL *)audioUrl {
- NSError *error = nil;
- @try {
- self.audioFile = [[AVAudioFile alloc] initForReading:audioUrl error:&error];
- self.audioFormat = self.audioFile.processingFormat;
- self.totalDuration = (AVAudioFramePosition)self.audioFile.length * 1000.0 / self.audioFormat.sampleRate;
- } @catch (NSException *exception) {
- self.audioFile = nil;
- self.audioFormat = nil;
- } @finally {
- if (error) {
- // 错误回调
- if (self.delegate && [self.delegate respondsToSelector:@selector(enginePlayerDidError:error:)]) {
- [self.delegate enginePlayerDidError:self error:error];
- }
- }
- }
-
- }
- - (void)prepareNativeSongWithUrl:(NSURL *)nativeMusicUrl {
- [self loadAudioFile:nativeMusicUrl];
-
- if (self.audioFile && self.audioFormat) {
- [self configEngine];
- // connect node
- [self.audioEngine connect:self.bgPlayer to:self.timePitchUnit format:self.audioFormat];
- [self.audioEngine connect:self.timePitchUnit to:self.audioEngine.mainMixerNode format:self.audioFormat];
-
- [self.audioEngine prepare];
-
- [self startEngine];
- if (self.audioEngine && self.audioEngine.isRunning) {
- if (self.delegate && [self.delegate respondsToSelector:@selector(enginePlayerIsReadyPlay:)]) {
- [self.delegate enginePlayerIsReadyPlay:self];
- }
- }
- }
-
- }
- - (void)startEngine {
- // 启动engine
- NSError *error = nil;
- @try {
- [self.audioEngine startAndReturnError:&error];
- } @catch (NSException *exception) {
-
- } @finally {
- if (error) {
- self.audioEngine = nil;
- // 错误回调
- if (self.delegate && [self.delegate respondsToSelector:@selector(enginePlayerDidError:error:)]) {
- [self.delegate enginePlayerDidError:self error:error];
- }
- }
- }
- }
- - (void)startPlay {
- if (self.audioEngine.isRunning == NO) {
- [self startEngine];
- }
- if (self.audioEngine.isRunning) {
- [self.bgPlayer play];
- self.isPlaying = YES;
- [self startTimer];
- }
- }
- - (void)stopPlay {
- [self stopTimer];
- self.isPlaying = NO;
- if (self.bgPlayer.isPlaying) {
- [self.bgPlayer stop];
- }
- }
- // 从某个位置开始播放 ms
- - (void)seekToTimePlay:(NSInteger)time {
- if (self.audioEngine.isRunning == NO) {
- [self startEngine];
- }
- if (self.audioEngine.isRunning) {
- [self playAudioWithStartTime:time];
- }
- }
- - (void)playAudioWithStartTime:(NSTimeInterval)startTime {
-
- if (self.audioEngine.isRunning == NO) {
- [self startEngine];
- }
- if (self.bgPlayer.isPlaying) {
- [self.bgPlayer stop];
- }
-
- AVAudioFramePosition startPosition = startTime / 1000.0 * self.audioFormat.sampleRate;
- self.startPosition = startPosition;
- AVAudioFrameCount frameCount = (AVAudioFrameCount)(self.audioFile.length - startPosition);
- if (frameCount > 0) {
- [self.bgPlayer scheduleSegment:self.audioFile startingFrame:startPosition frameCount:frameCount atTime:nil completionHandler:^{
-
- }];
-
-
- if (self.audioEngine.isRunning) {
- [self.bgPlayer play];
- [self startTimer];
- self.isPlaying = YES;
- }
- }
- else { // 已无后续片段
- // 播放完成
- if (self.delegate && [self.delegate respondsToSelector:@selector(enginePlayFinished:)]) {
- [self.delegate enginePlayFinished:self];
- }
- }
- }
- - (void)freePlayer {
-
- if (self.isPlaying) {
- [self stopPlay];
- }
- }
- - (void)startTimer {
- [self.timer setFireDate:[NSDate distantPast]];
- }
- - (void)stopTimer {
-
- [self.timer setFireDate:[NSDate distantFuture]];//暂停计时器
- }
- #pragma mark ----- lazying
- - (NSTimer *)timer{
-
- if (!_timer) {
- MJWeakSelf;
- _timer = [NSTimer scheduledTimerWithTimeInterval:0.01 repeats:YES block:^(NSTimer * _Nonnull timer) {
- [weakSelf timeFunction];
- }];
- [[NSRunLoop currentRunLoop] addTimer:_timer forMode:NSRunLoopCommonModes];
- [_timer setFireDate:[NSDate distantFuture]];
- }
- return _timer;
- }
- - (void)timeFunction {
- NSTimeInterval currentTime = [self getCurrentPlayTime];
- float progress = currentTime / self.totalDuration;
- NSDate *date = [NSDate date];
- NSTimeInterval inteveral = [date timeIntervalSince1970];
- if (self.delegate && [self.delegate respondsToSelector:@selector(updatePlayProgress:andTotalTime:andProgress:currentInterval:inPlayer:)]) {
- [self.delegate updatePlayProgress:currentTime andTotalTime:self.totalDuration andProgress:progress currentInterval:inteveral*1000 inPlayer:self];
- }
- }
- - (void)setRate:(float)rate {
- _rate = rate;
- float speed = rate;
- if (self.timePitchUnit) {
- self.timePitchUnit.rate = speed;
- }
- }
- - (void)setIsMute:(BOOL)isMute {
- _isMute = isMute;
- if (self.bgPlayer) {
- self.bgPlayer.volume = isMute ? 0.0 : 1.0;
- }
- }
- - (AVAudioUnitTimePitch *)timePitchUnit {
- if (!_timePitchUnit) {
- _timePitchUnit = [[AVAudioUnitTimePitch alloc] init];
- }
- return _timePitchUnit;
- }
- - (NSTimeInterval)getCurrentPlayTime {
- AVAudioTime *nodeTime = [self.bgPlayer lastRenderTime];
- if (nodeTime.sampleTimeValid && nodeTime.hostTimeValid && nodeTime && self.audioFile) {
-
- AVAudioTime *playerTime = [self.bgPlayer playerTimeForNodeTime:nodeTime];
- double sampleRate = [playerTime sampleRate];
- double elapsedSamples = (double)[playerTime sampleTime] + self.startPosition;
- if (elapsedSamples <= 0) {
- elapsedSamples = 0;
- }
- NSTimeInterval currentTime = elapsedSamples / sampleRate;
- NSLog(@"当前时间----- %f",currentTime*1000);
- return currentTime*1000;
- }
- else {
- return 0;
- }
- }
- - (void)dealloc {
- [[NSNotificationCenter defaultCenter] removeObserver:self];
- NSLog(@"---------AudioEnginePlayer dealloc ");
- if (_timer) {
- [_timer invalidate];
- _timer = nil;
- }
- }
- @end
|