RelaxBodyView.m 16.8 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 424
//
//  RelaxBodyView.m
//  DreamSleep
//
//  Created by peter on 2022/6/6.
//

#import "RelaxBodyView.h"
#import "RelaxTrainModel.h"
#import <FSAudioController.h>
#import "RelaxTrainCell.h"
#import "RelaxTrainRequestModel.h"

@interface RelaxBodyView () <UIGestureRecognizerDelegate, UICollectionViewDelegate, UICollectionViewDataSource>
@property (nonatomic, strong) UIButton *playerBtn;
@property (nonatomic, strong) UILabel *titleLab;
@property (nonatomic, strong) UISlider *sliderView;
@property (nonatomic, strong) UILabel *proLeftLb;
@property (nonatomic, strong) UILabel *proRightLb;
@property (nonatomic, strong) UILabel *tipsLab;
@property (nonatomic, strong) FSAudioStream *audioStream;
@property (nonatomic, strong) CADisplayLink *progressTimer;
@property (nonatomic, assign) BOOL isDraging;
@property (nonatomic, assign) FSAudioStreamState streamState;
@property (nonatomic, strong) UIView *relaxRecView;
@property (nonatomic, strong) UICollectionView *relaxCollectionView;
@property (nonatomic, strong) NSArray *relaxList;
@property (nonatomic, assign) NSInteger curIndex;
@property (nonatomic, assign) BOOL isUpdateTask;
@end

@implementation RelaxBodyView {
    UITapGestureRecognizer *_tapGesture;
}

- (instancetype)initWithFrame:(CGRect)frame {
    if (self = [super initWithFrame:frame]) {
        self.curIndex = 0;
        self.dk_backgroundColorPicker = DKColorPickerWithKey(VCViewBG);
        self.layer.cornerRadius = 26.0;
        self.layer.maskedCorners = kCALayerMinXMinYCorner | kCALayerMaxXMinYCorner;
        
        [self addSubview:self.playerBtn];
        [self addSubview:self.titleLab];
        [self addSubview:self.sliderView];
        [self addSubview:self.proLeftLb];
        [self addSubview:self.proRightLb];
        [self addSubview:self.tipsLab];
        [self addSubview:self.relaxRecView];
        [self addSubview:self.relaxCollectionView];
        
        [self.playerBtn mas_makeConstraints:^(MASConstraintMaker *make) {
            make.right.equalTo(self).offset(-45);
            make.top.equalTo(self).offset(-35);
        }];
        [self.titleLab mas_makeConstraints:^(MASConstraintMaker *make) {
            make.left.equalTo(self).offset(15);
            make.top.equalTo(self).offset(40);
        }];
        [self.sliderView mas_makeConstraints:^(MASConstraintMaker *make) {
            make.left.equalTo(self.mas_left).offset(38);
            make.right.equalTo(self.mas_right).offset(-37);
            make.height.equalTo(@15);
            make.top.equalTo(self.titleLab.mas_bottom).offset(11);
        }];
        [self.proLeftLb mas_makeConstraints:^(MASConstraintMaker *make) {
            make.left.equalTo(self.sliderView.mas_left);
            make.top.equalTo(self.sliderView.mas_bottom).offset(6);
            make.height.equalTo(@17);
            make.width.equalTo(@100);
        }];
        [self.proRightLb mas_makeConstraints:^(MASConstraintMaker *make) {
            make.right.equalTo(self.sliderView.mas_right);
            make.top.equalTo(self.sliderView.mas_bottom).offset(6);
            make.height.equalTo(@17);
            make.width.equalTo(@100);
        }];
        [self.tipsLab mas_makeConstraints:^(MASConstraintMaker *make) {
            make.left.equalTo(self.mas_left).offset(15);
            make.right.equalTo(self.mas_right).offset(-15);
            make.top.equalTo(self.sliderView.mas_bottom).offset(43);
        }];
        [self.relaxRecView mas_makeConstraints:^(MASConstraintMaker *make) {
            make.left.equalTo(self).offset(15);
            make.right.equalTo(self).offset(-15);
            make.top.equalTo(self.tipsLab.mas_bottom).offset(24);
            make.height.equalTo(@22);
        }];
        [self.relaxCollectionView mas_makeConstraints:^(MASConstraintMaker *make) {
            make.top.equalTo(self.relaxRecView.mas_bottom).offset(17);
            make.left.equalTo(self.relaxRecView);
            make.right.equalTo(self);
            make.bottom.equalTo(self).offset(-Bottom_SafeArea_Height);
        }];
        
        self.progressTimer = [CADisplayLink displayLinkWithTarget:[TimerProxy proxyWithTarget:self] selector:@selector(updateProgress)];
        [self.progressTimer addToRunLoop:[NSRunLoop mainRunLoop] forMode:NSRunLoopCommonModes];
    }
    return self;
}

- (void)dealloc {
    [self.progressTimer invalidate];
    self.progressTimer = nil;
}

- (void)playControlAction:(UIButton *)sender {
    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];
    }
}

#pragma mark - 解决按钮超出父视图区域无法点击
- (UIView *)hitTest:(CGPoint)point withEvent:(UIEvent *)event {
    UIView *view = [super hitTest:point withEvent:event];
    if (view == nil) {
        CGPoint tempPoint = [self.playerBtn convertPoint:point fromView:self];
        // 判断点击的点是否在按钮区域内
        if (CGRectContainsPoint(self.playerBtn.bounds, tempPoint)) {
            //返回按钮
            return self.playerBtn;
        }
    }
    return view;
}

- (void)updateProgress {
    if (self.isDraging == YES) return;
    
    FSStreamPosition cur = self.audioStream.currentTimePlayed;
    FSStreamPosition end = self.audioStream.duration;
    
    // 更新音频播放进度、音频当前播放时间、音频总时间
    self.sliderView.value = cur.position;
    self.proLeftLb.text = [NSString stringWithFormat:@"%02i:%02i", cur.minute, cur.second];
    self.proRightLb.text = [NSString stringWithFormat:@"%02i:%02i", end.minute, end.second];
}

- (void)refreshData:(NSArray *)listArr currentIndex:(NSInteger)index {
    if (listArr.count && index < listArr.count) {
        self.curIndex = index;
        RelaxTrainModel *relaxModel = listArr[index];
        [self refreshTopData:relaxModel isStartPlay:NO];
        
        self.relaxList = listArr;
        [self.relaxCollectionView reloadData];
    }
}

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

- (void)refreshTopData:(RelaxTrainModel *)relaxModel isStartPlay:(BOOL)isStartPlay {
    if (self.delegate && [self.delegate respondsToSelector:@selector(updateNaviTitleAndBgImg:)]) {
        [self.delegate updateNaviTitleAndBgImg:relaxModel];
    }
    
    self.titleLab.text = relaxModel.audio_name;
    NSString *audio_desc = [[NSString stringWithFormat:@"%@", relaxModel.audio_desc] stringByReplacingOccurrencesOfString:@"\\n" withString:@"\n"];
    self.tipsLab.height = [NSString getHeightWithText:audio_desc withFont:SysFont(14.0) withMaxWidth:kScreenWidth - 30];
    self.tipsLab.text = audio_desc;
    
    // 不是正在播放的状态需要先停止
    if (self.audioStream.isPlaying == NO) { [self.audioStream stop]; }
    self.audioStream.url = [NSURL URLWithString:relaxModel.audio_url];
    if (isStartPlay) { [self.audioStream play]; }
}

#pragma mark - UIGestureRecognizerDelegate
- (void)actionTapGesture:(UITapGestureRecognizer *)sender {
    CGPoint touchPoint = [sender locationInView:self.sliderView];
    float value = (self.sliderView.maximumValue - self.sliderView.minimumValue) * (touchPoint.x / self.sliderView.width);
    [self.sliderView setValue:value animated:YES];
    
    [self didSliderTouchEnded:value];
}

#pragma mark - 滑块事件
- (void)sliderValueChanged:(UISlider *)sender {
    self.isDraging = YES;
}

- (void)sliderTouchDown:(UISlider *)sender {
    _tapGesture.enabled = NO;
    self.isDraging = YES;
}

- (void)sliderTouchUpInSide:(UISlider *)sender {
    _tapGesture.enabled = YES;
    
    [self didSliderTouchEnded:sender.value];
}

- (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];
}

#pragma mark - UICollectionViewDelegate && UICollectionViewDataSource
- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section {
    return self.relaxList.count;
}

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath {
    RelaxTrainCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:NSStringFromClass([RelaxTrainCell class]) forIndexPath:indexPath];
    [cell updateRelaxCell:self.relaxList[indexPath.row] isShowPlayIcon:(self.curIndex == indexPath.row)];
    return cell;
}

- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath {
    if (self.curIndex == indexPath.row) {
        return;
    }
    self.curIndex = indexPath.row;
    RelaxTrainModel *relaxModel = [self.relaxList objectAtIndex:indexPath.row];
    [self refreshTopData:relaxModel isStartPlay:YES];
    [self.relaxCollectionView reloadData];
}

#pragma mark - lazy
- (UIButton *)playerBtn {
    if (!_playerBtn) {
        _playerBtn = [UIButton new];
        [_playerBtn addTarget:self action:@selector(playControlAction:) forControlEvents:UIControlEventTouchUpInside];
        [_playerBtn dk_setBackgroundImage:DKImagePickerWithNames(@"audio_play_icon", @"audio_play_icon", @"audio_play_icon") forState:UIControlStateNormal];
        [_playerBtn dk_setBackgroundImage:DKImagePickerWithNames(@"relax_pause", @"relax_pause", @"relax_pause") forState:UIControlStateSelected];
    }
    return _playerBtn;
}

- (UILabel *)titleLab {
    if (!_titleLab) {
        _titleLab = [UILabel dkLabWithFont:BoldFont(16.0)];
    }
    return _titleLab;
}

- (UISlider *)sliderView {
    if (!_sliderView) {
        _sliderView = [UISlider new];
        [_sliderView cornerRadius:2.0];
        _sliderView.minimumTrackTintColor = BrandColor;
        _sliderView.maximumTrackTintColor = ColorFromHex(0xE3E1E1);
        [_sliderView setThumbImage:[UIImage imageNamed:@"muse_slider_thumbImage"] forState:UIControlStateNormal];
        [_sliderView addTarget:self action:@selector(sliderValueChanged:) forControlEvents:UIControlEventValueChanged];
        [_sliderView addTarget:self action:@selector(sliderTouchDown:) forControlEvents:UIControlEventTouchDown];
        [_sliderView addTarget:self action:@selector(sliderTouchUpInSide:) forControlEvents:UIControlEventTouchUpInside];
        
        // 为UISlider添加点击事件
        _tapGesture = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(actionTapGesture:)];
        _tapGesture.delegate = self;
        [_sliderView addGestureRecognizer:_tapGesture];
    }
    return _sliderView;
}

- (UILabel *)tipsLab {
    if (!_tipsLab) {
        _tipsLab = [UILabel labWithFont:SysFont(14.0)];
        _tipsLab.dk_textColorPicker = DKColorPickerWithColors(SubTitleColor, ColorFromHexA(0xFFFFFF, .5), DSWhite);
        _tipsLab.numberOfLines = 0;
        _tipsLab.lineBreakMode = NSLineBreakByWordWrapping;
    }
    return _tipsLab;
}

- (UILabel *)proLeftLb {
    if (!_proLeftLb) {
        _proLeftLb = [UILabel labWithFont:SysFont(12)];
        _proLeftLb.textAlignment = NSTextAlignmentLeft;
        _proLeftLb.dk_textColorPicker = DKColorPickerWithColors(ColorFromHex(0xAAAAAA), ColorFromHex(0x5A6073), DSWhite);
    }
    return _proLeftLb;
}

- (UILabel *)proRightLb {
    if (!_proRightLb) {
        _proRightLb = [UILabel labWithFont:SysFont(12)];
        _proRightLb.textAlignment = NSTextAlignmentRight;
        _proRightLb.dk_textColorPicker = DKColorPickerWithColors(ColorFromHex(0xAAAAAA), ColorFromHex(0x5A6073), DSWhite);
    }
    return _proRightLb;
}

- (FSAudioStream *)audioStream {
    if (_audioStream == nil) {
        _audioStream = [[FSAudioStream alloc] init];
        _audioStream.strictContentTypeChecking = NO;
        _audioStream.defaultContentType = @"audio/mpeg";
        
        WS(weakSelf);
        [_audioStream setOnStateChange:^(FSAudioStreamState state) {
            weakSelf.streamState = state;
            weakSelf.playerBtn.selected = 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...");
                    
                    // 更新腹式呼吸放松法任务状态
                    @synchronized (weakSelf) {
                        if (weakSelf.isUpdateTask == NO) {
                            [RelaxTrainRequestModel userCurTaskStateWithParams:weakSelf.updateParams completion:^(RelaxTrainRequestModel * _Nonnull requestModel) {
                                if (requestModel.resCode == DSResCodeSuccess) {
                                    weakSelf.isUpdateTask = YES;
                                }
                            }];
                        }
                    }
                    
                    break;
                case kFsAudioStreamFailed:
                    [UIApplication sharedApplication].networkActivityIndicatorVisible = NO;
                    DSLog(@"音频文件加载失败");
                    break;
                case kFsAudioStreamPlaybackCompleted:
                    break;
                case kFsAudioStreamRetryingStarted:
                    DSLog(@"回放失败");
                    break;
                case kFsAudioStreamRetryingSucceeded:
                    DSLog(@"重试成功");
                    break;
                case kFsAudioStreamRetryingFailed:
                    DSLog(@"Failed to retry playback -- 重试失败");
                    break;
                default:
                    break;
            }
        }];
    }
    return _audioStream;
}

- (UIView *)relaxRecView {
    if (!_relaxRecView) {
        _relaxRecView = [UIView new];
        
        UIView *icon = [UIView new];
        icon.backgroundColor = BrandColor;
        [icon cornerRadius:2.0];
        [_relaxRecView addSubview:icon];
        
        UILabel *lab = [UILabel dkLabWithText:@"放松训练|推荐" font:BoldFont(16.0)];
        [_relaxRecView addSubview:lab];
        
        [icon mas_makeConstraints:^(MASConstraintMaker *make) {
            make.left.equalTo(_relaxRecView);
            make.top.equalTo(_relaxRecView).offset(2);
            make.bottom.equalTo(_relaxRecView).offset(-2);
            make.width.equalTo(@4);
        }];
        [lab mas_makeConstraints:^(MASConstraintMaker *make) {
            make.left.equalTo(icon.mas_right).offset(4);
            make.top.bottom.equalTo(icon);
        }];
    }
    return _relaxRecView;
}

- (UICollectionView *)relaxCollectionView {
    if (!_relaxCollectionView) {
        CGFloat width = 120;
        CGFloat height = 150;
        UICollectionViewFlowLayout *layout = [[UICollectionViewFlowLayout alloc] init];
        layout.sectionInset = UIEdgeInsetsMake(0, 0, 0, 15);
        layout.itemSize = CGSizeMake(width, height);
        layout.minimumLineSpacing = 12;
        layout.scrollDirection = UICollectionViewScrollDirectionHorizontal;
        _relaxCollectionView = [[UICollectionView alloc] initWithFrame:CGRectZero collectionViewLayout:layout];
        _relaxCollectionView.showsHorizontalScrollIndicator = NO;
        _relaxCollectionView.delegate = self;
        _relaxCollectionView.dataSource = self;
        [_relaxCollectionView registerClass:[RelaxTrainCell class] forCellWithReuseIdentifier:NSStringFromClass([RelaxTrainCell class])];
        _relaxCollectionView.backgroundColor = DSClearColor;
    }
    return _relaxCollectionView;
}

- (NSArray *)relaxList {
    if (!_relaxList) {
        _relaxList = [NSArray array];
    }
    return _relaxList;
}

@end