使用 UIPickerView 實作歌詞滾動,可以把它想成一個資料驅動的滾動列表。重點是把歌詞解析成模型,讓音訊播放進度驅動 PickerView 捲動。
可把 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];
}- (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 更新都應在主執行緒進行,避免畫面卡頓或狀態不一致。