公司做的一款教育App中,有個(gè)BookReading模塊是孩子用來學(xué)習(xí)英語,里面又有一個(gè)子模塊Listen用來播放句子,產(chǎn)品的需求是要求單詞跟隨著句子的播放而高亮,效果如下;GitHubDemo地址下載,這種需求之前沒做過,網(wǎng)上搜索的也沒有資料(有的也是歌詞的高亮),所以花費(fèi)了點(diǎn)時(shí)間,現(xiàn)在趁閑暇時(shí)間寫了個(gè)小小的demo,和大家分享,整個(gè)代碼寫的比較基礎(chǔ),有相似需求的可以借鑒,不懂的地方歡迎相互交流

wordHilightGif.gif
整體思路
1、根據(jù)服務(wù)器提供的json數(shù)據(jù)格式,demo中即為lrc.json,知道每個(gè)單詞都有讀的對(duì)應(yīng)的開始時(shí)間,

lrcjson.png
其中我定義了一個(gè)
var wordRanges = [NSRange](),用來存儲(chǔ)每個(gè)單詞的Range,用來匹配相應(yīng)單詞的高亮。
let textStr: NSString = section!.text
self.wordRanges.removeAll() // 在下一次添加之前,得先刪除之前的
weak var weakSelf = self
textStr.enumerateSubstringsInRange(NSMakeRange(0, textStr.length), options: .ByWords) { (substring, substringRange, enclosingRange, bb) in
weakSelf!.wordRanges.append(substringRange)
}
2、使用CADisplayLink添加到mainRunloop中,來實(shí)現(xiàn)不停的重繪UI工作,相比于定時(shí)器精確度更高
private func setupTimer() {
displayLink = CADisplayLink(target: self, selector: #selector(BookCollectionViewController.displayWord))
displayLink?.addToRunLoop(NSRunLoop.mainRunLoop(), forMode: NSDefaultRunLoopMode) // mode 為 NSRunLoopCommonModes
// 調(diào)用的頻率 默認(rèn)為值1,代表60Hz,即每秒刷新60次,調(diào)用每秒 displayWord() 60次,這里設(shè)置為10,代表6Hz
displayLink?.frameInterval = 10
}
核心代碼如下:
func displayWord() {
let cell = self.collectionView.visibleCells().first as! BookCollectionViewCell
let indexPath = collectionView.indexPathForCell(cell)
guard let page = model?.pages[(indexPath?.item)!] else {return}
guard let section = page.sections.first else {return}
var i = 0
while true {
let curTime = audioPlayer?.currentTime ?? 0 // 播放聲音的的時(shí)間,ms
guard (wordRanges.first != nil) else {break}
let word = section.words[i]
let curRange = wordRanges[i]
if Int(curTime * 1000) >= Int(word.cueStartMs) { // 拿當(dāng)前播放的聲音時(shí)間與json每個(gè)單詞的開始讀取時(shí)間相比,
attributeStr?.addAttributes([NSForegroundColorAttributeName: UIColor.whiteColor()], range: NSMakeRange(0, attributeStr!.length))
attributeStr?.addAttributes([NSForegroundColorAttributeName: UIColor.redColor()], range: curRange)
cell.content.attributedText = attributeStr
}
i += 1
if i >= wordRanges.count || i >= section.words.count {
break
}
}
}