標籤:ios 音樂 同步
最終:
模型
//// Sentence.h// 36_聲詞同步//// Created by beyond on 14-9-12.// Copyright (c) 2014年 com.beyond. All rights reserved.// 模型,句子#import <Foundation/Foundation.h>@interface Sentence : NSObject// 文字@property (nonatomic, copy) NSString *text;// 在音頻檔案中,朗誦開始的時間@property (nonatomic, assign) double startTime;@end
控制器
//// BeyondController.m// 36_聲詞同步//// Created by beyond on 14-9-12.// Copyright (c) 2014年 com.beyond. All rights reserved.//#import "BeyondController.h"#import "Sentence.h"#import "SongTool.h"@interface BeyondController ()// 句子物件數組@property (nonatomic, strong) NSArray *sentenceArr;// 開始播放就開啟時鐘,監聽 音樂的播放進度@property (nonatomic, strong) CADisplayLink *link;// 音樂播放器 可以獲得當前播放的時間 【currentTime】@property (nonatomic, strong) AVAudioPlayer *sentencePlayer;@end@implementation BeyondController// 懶載入,需要時才建立 時鐘- (CADisplayLink *)link{ if (!_link) { // 綁定時鐘方法 self.link = [CADisplayLink displayLinkWithTarget:self selector:@selector(update)]; } return _link;}// 懶載入,需要時才建立 句子物件數組,從Plist中的字典數組,轉成對象數組- (NSArray *)sentenceArr{ if (!_sentenceArr) { self.sentenceArr = [Sentence objectArrayWithFilename:@"redStory.plist"]; } return _sentenceArr;}- (void)viewDidLoad{ [super viewDidLoad]; // 工具類播放音樂,並用成員變數記住 建立的播放器對象【可拿到播放的currentTime】 self.sentencePlayer = [SongTool playMusic:@"一東.mp3"]; // 播放背景音樂 [SongTool playMusic:@"Background.caf"]; // 同時,開啟時鐘 [self.link addToRunLoop:[NSRunLoop mainRunLoop] forMode:NSDefaultRunLoopMode]; self.tableView.contentInset = UIEdgeInsetsMake(20, 0, 0, 0);}#pragma mark - 時鐘方法// 重點~~~~時鐘綁定的方法- (void)update{ // 擷取當前播放的位置(第多少秒,比如第10秒) double currentTime = self.sentencePlayer.currentTime; // 遍曆,找出對應的一句 int count = self.sentenceArr.count; for (int i = 0; i<count; i++) { // 1.當前詞句 Sentence *s = self.sentenceArr[i]; // 2.獲得下一條句子物件 int next = i + 1; Sentence *nextS = nil; // 需防止越界 if (next < count) { nextS = self.sentenceArr[next]; } // 3.關鍵判斷,如果當前播放的時間,大於i對應的時間,並且小於i+1對應的時間 if (currentTime >= s.startTime && currentTime < nextS.startTime) { // 選中並高亮對應行的文字 NSIndexPath *path = [NSIndexPath indexPathForRow:i inSection:0]; [self.tableView selectRowAtIndexPath:path animated:YES scrollPosition:UITableViewScrollPositionTop]; break; } }}#pragma mark - tableView資料來源方法// 共多少行,即多少句- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{ return self.sentenceArr.count;}// 每一行的獨一無二的文字- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{ // 1.建立cell static NSString *cellID = @"Sentence"; UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cellID]; if (cell == nil) { cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:cellID]; } // 2.設定cell 獨一無二的資料 Sentence *s = self.sentenceArr[indexPath.row]; cell.textLabel.text = s.text; return cell;}@end
音樂播放工具類
iOS_36聲詞同步