最终效果图:
模型
// // 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音乐播放工具类
原文地址:http://blog.csdn.net/pre_eminent/article/details/39236711