@fiy-fish
2015-07-18T20:12:48.000000Z
字数 2176
阅读 1505
Objective-c
//[海阔天空+歌词][1]
//密码:S51T
//[海阔天空:歌词][2]
// main.m
// day07-01-歌词解析
//
// Created by Aaron on 15/7/9.
// Copyright (c) 2015年 Aaron. All rights reserved.
//
#import <Foundation/Foundation.h>
#import "LrcManager.h"
int main(int argc, const char * argv[]) {
@autoreleasepool {
LrcManager *manager = [[LrcManager alloc] init];
[manager readLrcFile:@"/Users/qianfeng/Desktop/海阔天空.txt"];
NSLog(@"%@",[manager searchLrcForTime:@"00:00.08"]);
}
return 0;
}
#import <Foundation/Foundation.h>
@interface LrcManager : NSObject
{
NSMutableArray *_timesArray;
NSMutableDictionary *_timeAndLrcDic;
}
-(void)readLrcFile:(NSString *)path;
-(NSString *)searchLrcForTime:(NSString *)timeStr;
@end
#import "LrcManager.h"
@implementation LrcManager
-(instancetype)init
{
if(self = [super init])
{
_timesArray = [NSMutableArray array];
_timeAndLrcDic = [NSMutableDictionary dictionary];
}
return self;
}
-(void)readLrcFile:(NSString *)path
{
NSString *str = [NSString stringWithContentsOfFile:path encoding:NSUTF8StringEncoding error:nil];
//NSLog(@"%@",str);
//按行切割
NSArray *lines = [str componentsSeparatedByString:@"\n"];
//解析每一行
[self pareAllLines:lines];
}
-(void)pareAllLines:(NSArray *)lines
{
for(NSString *oneLine in lines)
{
NSArray *array = [oneLine componentsSeparatedByString:@"]"];
// NSLog(@"---------");
NSLog(@"%ld",array.count);
NSLog(@"%@",array);
// NSLog(@"---------");
//[00:00.33 海阔天空
//判断是否有歌词
if(array.count > 1)
{
//求毫秒
NSInteger mSecond = [self returnMSecond:[array[0] substringFromIndex:1]];
//存储关系
[_timeAndLrcDic setObject:array[1] forKey:@(mSecond)];
[_timesArray addObject:@(mSecond)];
}
}
// NSLog(@"%@",_timeAndLrcDic);
// NSLog(@"%@",_timesArray);
}
// 00:00.33
-(NSInteger)returnMSecond:(NSString *)timeStr
{
NSInteger minute = [[timeStr substringToIndex:2] integerValue];
NSInteger second = [[timeStr substringWithRange:NSMakeRange(3, 2)] integerValue];
NSInteger mSecond = [[timeStr substringFromIndex:6] integerValue];
return (minute*60+second)*100+mSecond;
}
-(NSString *)searchLrcForTime:(NSString *)timeStr
{
NSInteger mSecond = [self returnMSecond:timeStr];
//查找数组里合适的时间点
for(int i = 0 ; i < [_timesArray count]; i++)
{
NSNumber *time = _timesArray[i];
if(mSecond < [time integerValue])
{
if(i == 0)
{
return nil;
}
else
{
NSString *lrc = [_timeAndLrcDic objectForKey:_timesArray[i-1]];
return lrc;
}
}
if(i == [_timesArray count]-1)
{
return nil;
}
}
return nil;
}
@end