美文网首页
解析歌词

解析歌词

作者: Dove_Q | 来源:发表于2016-09-29 10:35 被阅读14次
    #import "ViewController.h"
    
    @interface ViewController ()
    {
        NSString *_LRC;
        NSTimer *_timer;
    }
    @property (nonatomic, strong)NSDateFormatter *dateFormatter;
    @end
    
    @implementation ViewController
    
    - (void)viewDidLoad {
        [super viewDidLoad];
        //根据文件名和类型找到文件的路径
        NSString *LRCPath = [[NSBundle mainBundle] pathForResource:@"小幸运" ofType:@"lrc"];
        _LRC = [NSString stringWithContentsOfFile:LRCPath encoding:NSUTF8StringEncoding error:nil];
        
        _timer = [NSTimer scheduledTimerWithTimeInterval:0.01 target:self selector:@selector(didTime:) userInfo:nil repeats:YES];
    }
    
    - (void) didTime: (NSTimer *)timer {
        static double time = 0;
        //计时器每次都会加载,所以要进行懒加载
        NSDateFormatter *dateFormatter = self.dateFormatter;
        //设置时间格式
        dateFormatter.dateFormat = @"mm:ss.SS";
        //将double型转换成NSDate类型
        NSDate *date = [NSDate dateWithTimeIntervalSince1970:time];
        //将把date转换成自己定义的格式
        NSString *timeStr = [dateFormatter stringFromDate:date];
        
        NSString *resultLrc = [self parseLRC:_LRC andTimeStamp:timeStr];
        if (resultLrc.length) {
            NSLog(@"%@", resultLrc);
        }
        //加上计时器的变化时间
        time = time + timer.timeInterval;
    }
    
    - (NSString *)parseLRC: (NSString *)LRC andTimeStamp:(NSString *)timeStamp {
        NSArray *LRCArray = [LRC componentsSeparatedByString:@"\n"];
        __block NSString *targetStr;
        [LRCArray enumerateObjectsUsingBlock:^(NSString *obj, NSUInteger idx, BOOL * _Nonnull stop) {
            if ([obj containsString:timeStamp]) {
                targetStr = obj;
                *stop = YES;
            }
        }];
        NSArray *lrcArray = [targetStr componentsSeparatedByString:@"]"];
        NSString *lrc = [lrcArray.lastObject stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceCharacterSet]];
        return lrc;
    }
    
    - (NSDateFormatter *)dateFormatter {
        //懒加载,dateFormatter是实例变量
        if (!_dateFormatter) {
            _dateFormatter = [NSDateFormatter new];
        }
        return _dateFormatter;
    }
    @end
    

    相关文章

      网友评论

          本文标题:解析歌词

          本文链接:https://www.haomeiwen.com/subject/ncbkyttx.html