1.获取歌词文件
//获取歌词文件 -(void)analysisIrc{ _timeArr=[[NSMutableArray alloc]init]; _stringArr=[[NSMutableArray alloc]init]; NSDictionary *dic=[self.playlistArr objectAtIndex:self.currentNum]; NSDictionary *songInfo=[dic valueForKey:@"songinfo"]; NSString *lrcStr=[songInfo valueForKey:@"lrclink"]; if ([NSData dataWithContentsOfFile:[self getLocalFilePath]]) {//本地存在 NSLog(@"本地歌词"); self.lrcLabel.text=self.nameLabel.text; [self ana]; }else{//本地不存在 [NSURLConnection sendAsynchronousRequest:[NSMutableURLRequest requestWithURL:[NSURL URLWithString:lrcStr]] queue:[NSOperationQueue new] completionHandler:^(NSURLResponse * _Nullable response, NSData * _Nullable data, NSError * _Nullable connectionError) { if (data) { [data writeToFile:[self getLocalFilePath] atomically:YES]; NSLog(@"歌词准备完毕"); [self performSelectorOnMainThread:@selector(ana) withObject:nil waitUntilDone:YES]; } }]; } }
2.解析歌词文件
-(void)ana{
//获取歌词文件 NSString *lyc = [NSString stringWithContentsOfFile:[self getLocalFilePath] encoding:NSUTF8StringEncoding error:nil]; // NSLog(@"歌词----%@",lyc);
//每行为一个元素 NSArray *lycArray = [lyc componentsSeparatedByString:@" "]; for (int i = 0; i < [lycArray count]; i++) { NSString *lineString = [lycArray objectAtIndex:i]; NSArray *lineArray = [lineString componentsSeparatedByString:@"]"]; //行不为空,长度大于时间长度 if ([lineArray[0] length] > 8) { NSString *str1 = [lineString substringWithRange:NSMakeRange(3, 1)]; NSString *str2 = [lineString substringWithRange:NSMakeRange(6, 1)]; if ([str1 isEqualToString:@":"] && [str2 isEqualToString:@"."]) { for (int i = 0; i < lineArray.count - 1; i++) { //获取歌词部分 NSString *lrcString = [lineArray objectAtIndex:lineArray.count - 1]; //获取时间部分 NSString *timeString =[[lineArray objectAtIndex:i] substringWithRange:NSMakeRange(1, 5)];// [_timeArr addObject:timeString]; [_stringArr addObject:lrcString]; } } } } }
3.获取歌词文件路径的函数
///* //获取文件路径 //*/ -(NSString *)getLocalFilePath{ NSArray *arr=NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES); NSString *path=[arr objectAtIndex:0]; // NSString *filepath=[path stringByAppendingPathComponent:_selectedPlaylistCellModel.playUrl32]; NSDictionary *dic=[self.playlistArr objectAtIndex:self.currentNum]; NSDictionary *songInfo=[dic valueForKey:@"songinfo"]; NSString *filepath=[NSString stringWithFormat:@"%@/%@-%@.lrc",path,[songInfo valueForKey:@"author"],[songInfo valueForKey:@"title"]]; NSLog(@"%@",filepath); return filepath; }
4.展示歌词
if (self.timeArr) { //NSLog(@"歌词存在"); //NSLog(@"%@",lrcString); if ([self.timeArr containsObject:self.currentTimeLabel.text]) { // NSLog(@"更新"); int index=(int)[self.timeArr indexOfObject:self.currentTimeLabel.text]; //内容不为空时传值 if (![[self.stringArr objectAtIndex:index] isEqual:@""]) { NSLog(@"%@",[self.stringArr objectAtIndex:index]); self.lrcLabel.text=[self.stringArr objectAtIndex:index]; } } }