MusicPlayerController.m 15.1 KB
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423
//
//  MusicPlayerController.m
//  DreamSleep
//
//  Created by peter on 2022/5/7.
//

#import "MusicPlayerController.h"
#import "MusicPlayerView.h"
#import <FSAudioController.h>
#import "SubAudioModel.h"
#import "CourseDetailController.h"
#import <MediaPlayer/MediaPlayer.h>
#import <AVFoundation/AVFoundation.h>

@interface MusicPlayerController () <MusicPlayerViewDelegate, CourseDetailControllerDelegate>
@property (nonatomic, strong) MusicPlayerView *playerView;
/// AudioStream 播放器
@property (nonatomic, strong) FSAudioStream *audioStream;
/// 播放进度定时器
@property (nonatomic, strong) CADisplayLink *progressTimer;
/// 是否正在拖动滑块
@property (nonatomic, assign) BOOL isDraging;
/// streamState
@property (nonatomic, assign) FSAudioStreamState streamState;
@end

@implementation MusicPlayerController {
    // 控制中心信息
    NSMutableDictionary *_remoteInfoDictionary;
    // 是否进入后台
    BOOL _isBackground;
    // 其他应用是否正在播放
    BOOL _isOtherPlaying;
}

- (void)loadView {
    self.view = self.playerView;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    
    [self launchPlayer];
    
    WS(weakSelf);
    [self.audioStream setOnStateChange:^(FSAudioStreamState state) {
        weakSelf.streamState = state;
        weakSelf.playerView.isPlaying = state == kFsAudioStreamPlaying;
        [weakSelf.progressTimer setPaused:!(state == kFsAudioStreamPlaying)];
        switch (state) {
            case kFsAudioStreamRetrievingURL:
                [UIApplication sharedApplication].networkActivityIndicatorVisible = YES;
                DSLog(@"retrieving URL  -- 检索文件");
                break;
            case kFsAudioStreamStopped:
                [UIApplication sharedApplication].networkActivityIndicatorVisible = NO;
                DSLog(@"kFsAudioStreamStopped --- 停止播放了");
                break;
            case kFsAudioStreamBuffering: {
                [UIApplication sharedApplication].networkActivityIndicatorVisible = YES;
                DSLog(@"buffering --- 缓存中");
                break;
            }
            case kFsAudioStreamPaused:
                DSLog(@"暂停了");
                break;
            case kFsAudioStreamSeeking:
                [UIApplication sharedApplication].networkActivityIndicatorVisible = YES;
                DSLog(@"kFsAudioStreamSeeking -- 快进 或者 快退");
                break;
            case kFsAudioStreamPlaying:
                [UIApplication sharedApplication].networkActivityIndicatorVisible = NO;
                DSLog(@"播放ing...");
                [weakSelf didClickRemoteCommandCenter];
                break;
            case kFsAudioStreamFailed:
                [UIApplication sharedApplication].networkActivityIndicatorVisible = NO;
                DSLog(@"音频文件加载失败");
                break;
            case kFsAudioStreamPlaybackCompleted:
                [weakSelf audioStreamPlaybackCompleted];
                break;
            case kFsAudioStreamRetryingStarted:
                DSLog(@"回放失败");
                break;
            case kFsAudioStreamRetryingSucceeded:
                DSLog(@"重试成功");
                break;
            case kFsAudioStreamRetryingFailed:
                DSLog(@"Failed to retry playback -- 重试失败");
                break;
            default:
                break;
        }
    }];
    self.audioStream.onFailure = ^(FSAudioStreamError error, NSString *errorDescription) {
        DSLog(@"音频加载失败:%ld", error);
    };
    
    TimerProxy *proxy = [TimerProxy proxyWithTarget:self];
    self.progressTimer = [CADisplayLink displayLinkWithTarget:proxy selector:@selector(updateProgress)];
    [self.progressTimer addToRunLoop:[NSRunLoop mainRunLoop] forMode:NSRunLoopCommonModes];
    
    [self addPlayerObserver];
    [self addRemoteControlHandler];
}

- (void)dealloc {
    [self.progressTimer invalidate];
    self.progressTimer = nil;
    
    [[NSNotificationCenter defaultCenter] removeObserver:self name:UIApplicationWillResignActiveNotification object:nil];
    [[NSNotificationCenter defaultCenter] removeObserver:self name:UIApplicationDidBecomeActiveNotification object:nil];
    [[NSNotificationCenter defaultCenter] removeObserver:self name:AVAudioSessionInterruptionNotification object:nil];
    
    [[UIApplication sharedApplication] endReceivingRemoteControlEvents];
    MPRemoteCommandCenter *center = [MPRemoteCommandCenter sharedCommandCenter];
    [[center playCommand] removeTarget:self];
    [[center pauseCommand] removeTarget:self];
    [[center nextTrackCommand] removeTarget:self];
    [[center previousTrackCommand] removeTarget:self];
    [center.changePlaybackPositionCommand removeTarget:self];
}

- (void)addPlayerObserver {
    // 将要进入后台
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(playerWillResignActive) name:UIApplicationWillResignActiveNotification object:nil];
    // 已经进入前台
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(playerDidEnterForeground) name:UIApplicationDidBecomeActiveNotification object:nil];
    // 监听播放器被打断(别的软件播放音乐,来电话)
    [[NSNotificationCenter defaultCenter] addObserver:self
                                             selector:@selector(playerAudioBeInterrupted:)
                                                 name:AVAudioSessionInterruptionNotification
                                               object:[AVAudioSession sharedInstance]];
}

- (void)playerWillResignActive {
    _isBackground = YES;
}

- (void)playerDidEnterForeground {
    _isBackground = NO;
}

- (void)playerAudioBeInterrupted:(NSNotification *)notification {
    NSDictionary *userInfo = notification.userInfo;
    if ([userInfo[AVAudioSessionInterruptionTypeKey] integerValue] == 1) { // 打断开始
        [self pause];
    } else { // 打断结束
        if ([userInfo[AVAudioSessionInterruptionOptionKey] unsignedIntegerValue] == 1) {
            [self play];
        }
    }
}

#pragma mark - 息屏播放(通知栏、锁屏界面)
- (void)addPlayingCenterInfo {
    _remoteInfoDictionary = [NSMutableDictionary dictionary];
    
    SubAudioModel *audioModel = self.playAudios[self.currentIndex];
    
    _remoteInfoDictionary[MPMediaItemPropertyTitle] = audioModel.audio_name;
    _remoteInfoDictionary[MPMediaItemPropertyAlbumTitle] = @"小梦睡眠";
    NSData *imageData = [NSData dataWithContentsOfURL:[NSURL URLWithString:audioModel.audio_pic]];
    UIImage *artworkImg = [UIImage imageWithData:imageData];
    MPMediaItemArtwork *artwork = [[MPMediaItemArtwork alloc] initWithBoundsSize:artworkImg.size requestHandler:^UIImage * _Nonnull(CGSize size) {
        return artworkImg;
    }];
    _remoteInfoDictionary[MPMediaItemPropertyArtwork] = artwork;
    _remoteInfoDictionary[MPNowPlayingInfoPropertyPlaybackRate] = [NSNumber numberWithFloat:1.0];
    [MPNowPlayingInfoCenter defaultCenter].nowPlayingInfo = _remoteInfoDictionary;
}

- (void)updatePlayingCenterInfo {
    if (!_isBackground) { return; }
    _remoteInfoDictionary[MPNowPlayingInfoPropertyElapsedPlaybackTime] = [NSNumber numberWithDouble:self.audioStream.currentTimePlayed.playbackTimeInSeconds];
    _remoteInfoDictionary[MPMediaItemPropertyPlaybackDuration] = [NSNumber numberWithDouble:self.audioStream.duration.playbackTimeInSeconds];
    [MPNowPlayingInfoCenter defaultCenter].nowPlayingInfo = _remoteInfoDictionary;
}

- (void)addRemoteControlHandler {
    [[UIApplication sharedApplication] beginReceivingRemoteControlEvents];
    MPRemoteCommandCenter *center = [MPRemoteCommandCenter sharedCommandCenter];
    [self addRemoteCommand:center.playCommand selector:@selector(play)];
    [self addRemoteCommand:center.pauseCommand selector:@selector(pause)];
    [self addRemoteCommand:center.previousTrackCommand selector:@selector(last)];
    [self addRemoteCommand:center.nextTrackCommand selector:@selector(next)];
}

- (void)addRemoteCommand:(MPRemoteCommand *)command selector:(SEL)selector {
    WS(weaksSelf);
    [command addTargetWithHandler:^MPRemoteCommandHandlerStatus(MPRemoteCommandEvent * _Nonnull event) {
        if ([weaksSelf respondsToSelector:selector]) {
            IMP imp = [weaksSelf methodForSelector:selector];
            void (*func)(id, SEL) = (void *)imp;
            func(weaksSelf, selector);
        }
        return MPRemoteCommandHandlerStatusSuccess;
    }];
}

- (void)play {
    if (self.streamState == kFsAudioStreamStopped || self.streamState == kFsAudioStreamRetrievingURL) {
        [self.audioStream play];
    }  else if (self.streamState == kFsAudioStreamPaused) {
        // 恢复播放
        [self.audioStream pause];
    }
    
    [self didClickRemoteCommandCenter];
}

- (void)pause {
    if (self.streamState == kFsAudioStreamPlaying) {
        // 暂停播放
        [self.audioStream pause];
    }
    
    [self didClickRemoteCommandCenter];
}

- (void)last {
    if (self.currentIndex - 1 < 0) {
        [DSProgressHUD showToast:@"没有上一首了"];
        return;
    }
    self.currentIndex--;
    [self launchPlayer];
}

- (void)next {
    if (self.currentIndex + 1 >= self.playAudios.count) {
        [DSProgressHUD showToast:@"没有下一首了"];
        return;
    }
    self.currentIndex++;
    [self launchPlayer];
}

- (void)didClickRemoteCommandCenter {
    NSInteger playingIndex = self.audioStream.isPlaying ? self.currentIndex : -1;
    [[NSNotificationCenter defaultCenter] postNotificationName:RemoteCommandCenterDidClick object:nil userInfo:@{@"playingIndex":@(playingIndex)}];
}

#pragma mark - private
- (void)updateProgress {
    if (self.isDraging == YES) return;
    
    FSStreamPosition cur = self.audioStream.currentTimePlayed;
    FSStreamPosition end = self.audioStream.duration;
    
    // 更新音频播放进度、音频当前播放时间、音频总时间
    [self.playerView updateProgress:cur.position currentTime:[NSString stringWithFormat:@"%02i:%02i", cur.minute, cur.second] totalTime:[NSString stringWithFormat:@"%02i:%02i", end.minute, end.second]];
    
    // DSLog(@"缓存进度:%f, 总进度:%f", self.audioStream.prebufferedByteCount, self.audioStream.contentLength);
    
    [self updatePlayingCenterInfo];
}

- (void)audioStreamPlaybackCompleted {
    DSLog(@"kFsAudioStreamPlaybackCompleted -- 回放完成");
    if (self.playerView.mode == SoundPlayModeSingle) { // 单节播放:播放完当前音频就自动停止了
        [self reset];
    } else if (self.playerView.mode == SoundPlayModeCycle) { // 单曲循环
        [self.audioStream play];
    } else if (self.playerView.mode == SoundPlayModeOrder) { // 顺序播放
        // 播放列表最后一个音频
        if (self.currentIndex + 1 >= self.playAudios.count) {
            [self reset];
        } else {
            // 获取下一首需要播放的音频
            self.currentIndex++;
            [self launchPlayer];
        }
    }
}

- (void)reset {
    FSStreamPosition pos = {0};
    pos.position = 0;
    [self.audioStream seekToPosition:pos];
    FSStreamPosition end = self.audioStream.duration;
    [self.playerView updateProgress:0 currentTime:@"00:00" totalTime:[NSString stringWithFormat:@"%02i:%02i", end.minute, end.second]];
}

- (void)launchPlayer {
    [self.audioStream stop];
    
    if (self.currentIndex >= self.playAudios.count) { return; }
    SubAudioModel *audioModel = self.playAudios[self.currentIndex];
    [self.playerView updatePlayerView:audioModel];
    [self.audioStream playFromURL:[NSURL URLWithString:audioModel.audio_url]];
    
    // 设置音频锁屏界面信息
    [self addPlayingCenterInfo];
}

#pragma mark - MusicPlayerViewDelegate
- (void)didSliderTouchBegan:(float)value {
    self.isDraging = YES;
}

- (void)didSliderTouchEnded:(float)value {
    self.isDraging = NO;
    //  避免用户拖动进度条出现极值导致音频文件加载失败问题
    if (value == 0) value = 0.001;
    if (value == 1) value = 0.999;
    
    FSStreamPosition pos = {0};
    pos.position = value;
    [self.audioStream seekToPosition:pos];
}

- (void)didSliderValueChange:(float)value {
    self.isDraging = YES;
}

- (void)playControlActionWithItem:(UIButton *)item {
    switch (item.tag) {
        case 1: // 上一首
        {
            [self last];
        }
            break;
        case 2: // 播放暂停
        {
            if (self.streamState == kFsAudioStreamStopped || self.streamState == kFsAudioStreamRetrievingURL) {
                [self.audioStream play];
            } else if (self.streamState == kFsAudioStreamPlaying) {
                // 暂停播放
                [self.audioStream pause];
            } else if (self.streamState == kFsAudioStreamPaused) {
                // 恢复播放
                [self.audioStream pause];
            }
        }
            break;
        case 3: // 下一首
        {
            [self next];
        }
            break;
        default:
            break;
    }
}

- (void)timerHasCountDone {
    if (self.streamState == kFsAudioStreamPlaying) {
        [self.audioStream pause];
    }
}

- (void)jumpToPlaylistController {
    CourseDetailController *coureDetailVC = [[CourseDetailController alloc] init];
    coureDetailVC.courseModel = self.courseModel;
    coureDetailVC.playingIndex = self.audioStream.isPlaying ? self.currentIndex : -1;
    coureDetailVC.isFromPlayer = YES;
    coureDetailVC.courseType = self.courseType;
    coureDetailVC.delegate = self;
    coureDetailVC.entrance = EntrancePlayer;
    [self.navigationController pushViewController:coureDetailVC animated:YES];
}

- (void)stopAudioAndDismiss {
    if (self.streamState == kFsAudioStreamPlaying) {
        [self.audioStream pause];
    }
    [self.audioStream stop];
    [self dismissViewControllerAnimated:YES completion:nil];
}

#pragma mark - CourseDetailControllerDelegate
- (void)didSelectAudioWithIndex:(NSInteger)index latestAudios:(NSArray *)audios {
    // 更新音频数据
    self.playAudios = audios;
    
    // 点击当前传过来音频
    if (self.currentIndex == index) {
        if (self.streamState == kFsAudioStreamStopped || self.streamState == kFsAudioStreamRetrievingURL) {
            [self.audioStream play];
        } else if (self.streamState == kFsAudioStreamPaused) {
            // 恢复播放
            [self.audioStream pause];
        }
        return;
    }
    self.currentIndex = index;
    [self launchPlayer];
}

#pragma mark - 隐藏导航栏
- (BOOL)isShowNavigationBar {
    return YES;
}

#pragma mark - 设置状态栏文字颜色
- (UIStatusBarStyle)preferredStatusBarStyle {
    return [self.dk_manager.themeVersion isEqualToString:DKThemeVersionNormal] ? UIStatusBarStyleDefault : UIStatusBarStyleLightContent;
}

#pragma mark - lazy
- (MusicPlayerView *)playerView {
    if (!_playerView) {
        _playerView = [MusicPlayerView new];
        _playerView.delegate = self;
    }
    return _playerView;
}

- (FSAudioStream *)audioStream {
    if (_audioStream == nil) {
        _audioStream = [[FSAudioStream alloc] init];
        _audioStream.strictContentTypeChecking = NO;
        _audioStream.defaultContentType = @"audio/mpeg";
        _audioStream.volume = .5;
        [_audioStream setPlayRate:1.0];
    }
    return _audioStream;
}

@end