听书简单应用

来源:互联网 发布:淘宝游戏专营还会开吗 编辑:程序博客网 时间:2024/05/17 04:45
听书

主要代码

#import "XJViewController.h"

#import "XJWord.h"

#import "MJExtension.h"

#import "XJAduioTool.h"


@interface XJViewController ()

@property (nonatomic, strong) NSArray *words;


@property (nonatomic, strong) CADisplayLink *link;


@property (nonatomic, strong) AVAudioPlayer *audioPlayer;

@end


@implementation XJViewController




- (void)viewDidLoad

{

    [super viewDidLoad];

    

    // 播放背景音乐

    [XJAduioTool playMusicWithMusicName:@"Background.caf"];

    

    // 播放朗诵音乐

  self.audioPlayer = [XJAduioTool playMusicWithMusicName:@"一东.mp3"];

    

    // 开启定时器

    [self.link addToRunLoop:[NSRunLoop mainRunLoop ] forMode:NSDefaultRunLoopMode];

    

}


#pragma mark - tableView的代理

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section

{

    return self.words.count;

}


- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath

{

    // 1.创建cell

    static NSString *ID = @"word";

    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:ID];

    if (cell == nil) {

        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:ID];

    }

    

    // 2.设置cell的数据

    XJWord *word = self.words[indexPath.row];

    cell.textLabel.text = word.text;

    

    return cell;

}


#pragma mark - 懒加载

-(NSArray *)words

{

    if (!_words) {

        self.words = [XJWord objectArrayWithFilename:@"一东.plist"];

    }

    return _words;

}

- (CADisplayLink *)link

{

    if (_link == nil) {

        _link = [CADisplayLink displayLinkWithTarget:self selector:@selector(updata)];

    }

    return _link;

}


- (void)updata

{

    double currentime = self.audioPlayer.currentTime;

    

    // 遍历取出上下两行的时间段,然后跟当前的时间进行比较,然后tableview就选择那一行

    for (int i = 0; i < self.words.count; i ++) {

        

        //当前词句

        XJWord *cureetWord = self.words[i];

        

        // 下一条词句

        int next = i;

        if (next < self.words.count - 1) {

            next ++;

        }

        

        XJWord *nextWord = self.words[next];

        

        if (currentime >= cureetWord.time && currentime <= nextWord.time) {

            

            // 主动选择下一行

            NSIndexPath *indexPath = [NSIndexPath indexPathForRow:i inSection:0];

            [self.tableView selectRowAtIndexPath:indexPath animated:0 scrollPosition:UITableViewScrollPositionNone];

        }

        

   

    }

    

}

0 0