您现在的位置: IOS教程網 >> IOS系統 >  >> iOS 程式開發 >> iOS 開發綜合

iOS 開發練習之 UIPickerView 實現歌詞滾動效果

編輯:iOS 開發綜合

使用 UIPickerView 實作歌詞滾動,可以把它想成一個資料驅動的滾動列表。重點是把歌詞解析成模型,讓音訊播放進度驅動 PickerView 捲動。

整體架構

  • Word:代表一行歌詞,包含時間與文字。
  • AudioPlayTool:封裝 AVAudioPlayer 的播放、暫停與停止。
  • CADisplayLink:持續追蹤播放進度。
  • UIPickerView:顯示歌詞並捲動到目前播放位置。

解析歌詞

可把 LRC 檔讀成字串,按行拆分,再取出時間與文字,建立 Word 物件陣列。

NSString *path = [[NSBundle mainBundle] pathForResource:@"歌詞" ofType:@"lrc"];
NSString *original = [NSString stringWithContentsOfFile:path encoding:NSUTF8StringEncoding error:nil];
NSArray *lines = [original componentsSeparatedByString:@"\n"];

更新目前歌詞

在 CADisplayLink 的回呼中取得 player.currentTime,與每行歌詞的時間比較,找到目前應該顯示的索引。

-(void)updateInfo:(CADisplayLink *)display {
    AVAudioPlayer *player = self.playTool.audioPlay;
    double currentTime = player.currentTime;

    for (int i = 0; i < self.wordsArray.count; i++) {
        Word *word = self.wordsArray[i];
        double wordTime = [NSString getTimeWithString:word.time];

        if (currentTime >= wordTime) {
            self.index = i;
        }
    }

    [self.wordListPicker selectRow:self.index inComponent:0 animated:YES];
}

PickerView 顯示

- (UIView *)pickerView:(UIPickerView *)pickerView viewForRow:(NSInteger)row forComponent:(NSInteger)component reusingView:(UIView *)view {
    UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, 320, 40)];
    Word *word = self.wordsArray[row];
    label.text = word.text;
    label.font = [UIFont systemFontOfSize:13];
    label.numberOfLines = 0;
    return label;
}

實作時要注意播放進度更新與 UI 更新都應在主執行緒進行,避免畫面卡頓或狀態不一致。

  1. 上一篇文章:
  2. 下一篇文章:
蘋果刷機越獄教程| IOS教程問題解答| IOS技巧綜合| IOS7技巧| IOS8教程
Copyright © IOS教程網 All Rights Reserved