AudioEnginePlayer.m 9.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308
  1. //
  2. // AudioEnginePlayer.m
  3. // KulexiuForStudent
  4. //
  5. // Created by 王智 on 2024/6/4.
  6. //
  7. #import "AudioEnginePlayer.h"
  8. #import <AVFoundation/AVFoundation.h>
  9. @interface AudioEnginePlayer ()
  10. /** 定时器 */
  11. @property (nonatomic, strong) NSTimer *timer;
  12. @property (nonatomic, strong) AVAudioEngine *audioEngine;
  13. @property (nonatomic, strong) AVAudioPlayerNode *bgPlayer;
  14. @property (nonatomic, strong) AVAudioUnitTimePitch *timePitchUnit;
  15. @property (nonatomic, strong) AVAudioFile *audioFile;
  16. @property (nonatomic, strong) AVAudioFormat *audioFormat;
  17. @property (nonatomic, assign) NSTimeInterval totalDuration;
  18. @property (nonatomic, assign) AVAudioFramePosition startPosition; // 开始位置
  19. @end
  20. @implementation AudioEnginePlayer
  21. - (instancetype)init {
  22. self = [super init];
  23. if (self) {
  24. }
  25. return self;
  26. }
  27. - (void)setupAudioSession {
  28. AVAudioSession *audioSession = [AVAudioSession sharedInstance];
  29. @try {
  30. NSError *err = nil;
  31. AVAudioSessionCategory category = AVAudioSessionCategoryPlayAndRecord;
  32. if (@available(iOS 10.0, *)) {
  33. [audioSession setCategory:category mode:AVAudioSessionModeDefault options:AVAudioSessionCategoryOptionAllowBluetooth|AVAudioSessionCategoryOptionAllowBluetoothA2DP|AVAudioSessionCategoryOptionDefaultToSpeaker|AVAudioSessionCategoryOptionMixWithOthers error:&err];
  34. }
  35. else {
  36. [audioSession setCategory:category withOptions:AVAudioSessionCategoryOptionAllowBluetooth|AVAudioSessionCategoryOptionDefaultToSpeaker|AVAudioSessionCategoryOptionMixWithOthers error:&err];
  37. }
  38. [audioSession setActive:YES error:&err];
  39. } @catch (NSException *exception) {
  40. NSLog(@"----- exception --- %@", exception);
  41. } @finally {
  42. [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(handleInterruption:) name:AVAudioSessionInterruptionNotification object:audioSession];
  43. }
  44. }
  45. // 打断处理
  46. - (void)handleInterruption:(NSNotification *)notification {
  47. NSDictionary *info = notification.userInfo;
  48. AVAudioSessionInterruptionType type = [info[AVAudioSessionInterruptionTypeKey] unsignedIntegerValue];
  49. if (type == AVAudioSessionInterruptionTypeBegan) {
  50. //Handle InterruptionBegan
  51. if (self.delegate && [self.delegate respondsToSelector:@selector(enginePlayerDidError:error:)]) {
  52. NSError *error = [[NSError alloc] initWithDomain:NSCocoaErrorDomain code:99999 userInfo:@{@"errorDesc" : @"播放被打断"}];
  53. [self.delegate enginePlayerDidError:self error:error];
  54. }
  55. }
  56. else {
  57. AVAudioSessionInterruptionOptions options = [info[AVAudioSessionInterruptionOptionKey] unsignedIntegerValue];
  58. if (options == AVAudioSessionInterruptionOptionShouldResume) {
  59. //Handle Resume
  60. [[AVAudioSession sharedInstance] setActive:YES error:nil];
  61. // [self startEngine];
  62. }
  63. }
  64. }
  65. - (void)configEngine {
  66. [self setupAudioSession];
  67. self.audioEngine = [[AVAudioEngine alloc] init];
  68. self.bgPlayer = [[AVAudioPlayerNode alloc] init];
  69. // attach node
  70. [self.audioEngine attachNode:self.bgPlayer];
  71. [self.audioEngine attachNode:self.timePitchUnit];
  72. }
  73. - (void)loadAudioFile:(NSURL *)audioUrl {
  74. NSError *error = nil;
  75. @try {
  76. self.audioFile = [[AVAudioFile alloc] initForReading:audioUrl error:&error];
  77. self.audioFormat = self.audioFile.processingFormat;
  78. self.totalDuration = (AVAudioFramePosition)self.audioFile.length * 1000.0 / self.audioFormat.sampleRate;
  79. } @catch (NSException *exception) {
  80. self.audioFile = nil;
  81. self.audioFormat = nil;
  82. } @finally {
  83. if (error) {
  84. // 错误回调
  85. if (self.delegate && [self.delegate respondsToSelector:@selector(enginePlayerDidError:error:)]) {
  86. [self.delegate enginePlayerDidError:self error:error];
  87. }
  88. }
  89. }
  90. }
  91. - (void)prepareNativeSongWithUrl:(NSURL *)nativeMusicUrl {
  92. [self loadAudioFile:nativeMusicUrl];
  93. if (self.audioFile && self.audioFormat) {
  94. [self configEngine];
  95. // connect node
  96. [self.audioEngine connect:self.bgPlayer to:self.timePitchUnit format:self.audioFormat];
  97. [self.audioEngine connect:self.timePitchUnit to:self.audioEngine.mainMixerNode format:self.audioFormat];
  98. [self.audioEngine prepare];
  99. [self startEngine];
  100. if (self.audioEngine && self.audioEngine.isRunning) {
  101. if (self.delegate && [self.delegate respondsToSelector:@selector(enginePlayerIsReadyPlay:)]) {
  102. [self.delegate enginePlayerIsReadyPlay:self];
  103. }
  104. }
  105. }
  106. }
  107. - (void)startEngine {
  108. // 启动engine
  109. NSError *error = nil;
  110. @try {
  111. [self.audioEngine startAndReturnError:&error];
  112. } @catch (NSException *exception) {
  113. } @finally {
  114. if (error) {
  115. self.audioEngine = nil;
  116. // 错误回调
  117. if (self.delegate && [self.delegate respondsToSelector:@selector(enginePlayerDidError:error:)]) {
  118. [self.delegate enginePlayerDidError:self error:error];
  119. }
  120. }
  121. }
  122. }
  123. - (void)startPlay {
  124. if (self.audioEngine.isRunning == NO) {
  125. [self startEngine];
  126. }
  127. if (self.audioEngine.isRunning) {
  128. [self.bgPlayer play];
  129. self.isPlaying = YES;
  130. [self startTimer];
  131. }
  132. }
  133. - (void)stopPlay {
  134. [self stopTimer];
  135. self.isPlaying = NO;
  136. if (self.bgPlayer.isPlaying) {
  137. [self.bgPlayer stop];
  138. }
  139. }
  140. // 从某个位置开始播放 ms
  141. - (void)seekToTimePlay:(NSInteger)time {
  142. if (self.audioEngine.isRunning == NO) {
  143. [self startEngine];
  144. }
  145. if (self.audioEngine.isRunning) {
  146. [self playAudioWithStartTime:time];
  147. }
  148. }
  149. - (void)playAudioWithStartTime:(NSTimeInterval)startTime {
  150. if (self.audioEngine.isRunning == NO) {
  151. [self startEngine];
  152. }
  153. if (self.bgPlayer.isPlaying) {
  154. [self.bgPlayer stop];
  155. }
  156. AVAudioFramePosition startPosition = startTime / 1000.0 * self.audioFormat.sampleRate;
  157. self.startPosition = startPosition;
  158. AVAudioFrameCount frameCount = (AVAudioFrameCount)(self.audioFile.length - startPosition);
  159. if (frameCount > 0) {
  160. [self.bgPlayer scheduleSegment:self.audioFile startingFrame:startPosition frameCount:frameCount atTime:nil completionHandler:^{
  161. }];
  162. if (self.audioEngine.isRunning) {
  163. [self.bgPlayer play];
  164. [self startTimer];
  165. self.isPlaying = YES;
  166. }
  167. }
  168. else { // 已无后续片段
  169. // 播放完成
  170. if (self.delegate && [self.delegate respondsToSelector:@selector(enginePlayFinished:)]) {
  171. [self.delegate enginePlayFinished:self];
  172. }
  173. }
  174. }
  175. - (void)freePlayer {
  176. if (self.isPlaying) {
  177. [self stopPlay];
  178. }
  179. }
  180. - (void)startTimer {
  181. [self.timer setFireDate:[NSDate distantPast]];
  182. }
  183. - (void)stopTimer {
  184. [self.timer setFireDate:[NSDate distantFuture]];//暂停计时器
  185. }
  186. #pragma mark ----- lazying
  187. - (NSTimer *)timer{
  188. if (!_timer) {
  189. MJWeakSelf;
  190. _timer = [NSTimer scheduledTimerWithTimeInterval:0.01 repeats:YES block:^(NSTimer * _Nonnull timer) {
  191. [weakSelf timeFunction];
  192. }];
  193. [[NSRunLoop currentRunLoop] addTimer:_timer forMode:NSRunLoopCommonModes];
  194. [_timer setFireDate:[NSDate distantFuture]];
  195. }
  196. return _timer;
  197. }
  198. - (void)timeFunction {
  199. NSTimeInterval currentTime = [self getCurrentPlayTime];
  200. float progress = currentTime / self.totalDuration;
  201. NSDate *date = [NSDate date];
  202. NSTimeInterval inteveral = [date timeIntervalSince1970];
  203. if (self.delegate && [self.delegate respondsToSelector:@selector(updatePlayProgress:andTotalTime:andProgress:currentInterval:inPlayer:)]) {
  204. [self.delegate updatePlayProgress:currentTime andTotalTime:self.totalDuration andProgress:progress currentInterval:inteveral*1000 inPlayer:self];
  205. }
  206. }
  207. - (void)setRate:(float)rate {
  208. _rate = rate;
  209. float speed = rate;
  210. if (self.timePitchUnit) {
  211. self.timePitchUnit.rate = speed;
  212. }
  213. }
  214. - (void)setIsMute:(BOOL)isMute {
  215. _isMute = isMute;
  216. if (self.bgPlayer) {
  217. self.bgPlayer.volume = isMute ? 0.0 : 1.0;
  218. }
  219. }
  220. - (AVAudioUnitTimePitch *)timePitchUnit {
  221. if (!_timePitchUnit) {
  222. _timePitchUnit = [[AVAudioUnitTimePitch alloc] init];
  223. }
  224. return _timePitchUnit;
  225. }
  226. - (NSTimeInterval)getCurrentPlayTime {
  227. AVAudioTime *nodeTime = [self.bgPlayer lastRenderTime];
  228. if (nodeTime.sampleTimeValid && nodeTime.hostTimeValid && nodeTime && self.audioFile) {
  229. AVAudioTime *playerTime = [self.bgPlayer playerTimeForNodeTime:nodeTime];
  230. double sampleRate = [playerTime sampleRate];
  231. double elapsedSamples = (double)[playerTime sampleTime] + self.startPosition;
  232. if (elapsedSamples <= 0) {
  233. elapsedSamples = 0;
  234. }
  235. NSTimeInterval currentTime = elapsedSamples / sampleRate;
  236. NSLog(@"当前时间----- %f",currentTime*1000);
  237. return currentTime*1000;
  238. }
  239. else {
  240. return 0;
  241. }
  242. }
  243. - (void)dealloc {
  244. [[NSNotificationCenter defaultCenter] removeObserver:self];
  245. NSLog(@"---------AudioEnginePlayer dealloc ");
  246. if (_timer) {
  247. [_timer invalidate];
  248. _timer = nil;
  249. }
  250. }
  251. @end