iOS歌词解析

  好不容易吧歌词解出来了,分享给大家。

  首先我定义了一个方法,把歌词的名字传进去,返回一个字典,key是以“:”分割的时间戳,值是当前行的歌词。

 

 1 -(NSMutableDictionary*)musicLrc:(NSString*)musicName
 2 {
 3     
 4     //    初始化一个字典
 5     NSMutableDictionary *musicLrcDictionary=[[NSMutableDictionary alloc]initWithCapacity:20];
 6     //    加载歌词到内存
 7     NSString *strMusicUrl=[[NSBundle mainBundle]pathForResource:musicName ofType:@"lrc"];
 8     NSString *strLrcKu=[NSString stringWithContentsOfFile:strMusicUrl encoding:NSUTF8StringEncoding error:nil];
 9     //    把文件安行分割,以每行为单位放入数组
10     NSArray *strlineArray=[strLrcKu componentsSeparatedByString:@"
"];
11     //    安行读取歌词歌词
12     for (int i=0; i<[strlineArray count]; i++) {
13         //      将时间和歌词分割
14         NSArray *lineComponents=[[strlineArray objectAtIndex:i] componentsSeparatedByString:@"]"];
15         //        取出每行的时间  注意有些歌词是重复使用的,所以会有多个时间点
16         for (int n=0; n<[lineComponents count]; n++) {
17             NSString *strKuTimer = lineComponents[n];
18             if ([strKuTimer length]==9) {
19                 //    取出“:”和“.”符号来对比,是否是我们所需要的时间
20                 NSString *str1=[strKuTimer substringWithRange:NSMakeRange(3, 1)];
21                 NSString *str2=[strKuTimer substringWithRange:NSMakeRange(6, 1)];
22                 if ([str1 isEqualToString:@":"]&&[str2 isEqualToString:@"."]) {
23                     //    将时间和歌词暂时放在两个字符串里
24                     NSString *lineTimer=[[lineComponents objectAtIndex:n] substringWithRange:NSMakeRange(1, 5)];
25                     NSString *lineStr=[lineComponents objectAtIndex:([lineComponents count]-1)];
26                     //    以时间为key,歌词为值,放入字典中
27                     [musicLrcDictionary setObject:lineStr forKey:lineTimer];
28                 }
29             }
30         }
31     }
32     //    在这里返回整个字典
33     return musicLrcDictionary;
34     
35 }

  完整的代码在我的github上有托管地址是:https://github.com/qisedao0215/audioPlay

  

原文地址:https://www.cnblogs.com/qisedao0215/p/3724423.html