iOS之基于FreeStreamer的简单音乐播放器示例

2020-01-21 02:24:13于海丽

 

复制代码
[self.lrcTableView scrollToRowAtIndexPath:currentIndexPath atScrollPosition:UITableViewScrollPositionMiddle animated:YES]

 

但是这中要注意一个问题,那就是必须做到,在下一行进行展示的时候,取消上一行的效果,如下


        //设置当前行的状态
        [currentCell reloadCellForSelect:YES];
        //取消上一行的选中状态
        [previousCell reloadCellForSelect:NO];

- (void)reloadCellForSelect:(BOOL)select
{
  if (select) {
    _lrcLable.font = [UIFont systemFontOfSize:17];
  }else{
    _lrcLable.font = [UIFont systemFontOfSize:14];
    _lrcLable.progress = 0;
  }
}

其中_lrcLable.progress = 0;必须要,否则我们的文字颜色不会改变

在大问题已经解决的情况下,我们就需要关心另一个重要的问题了,那就是歌词。这里先介绍一个网站,可以获取歌曲名和歌词的

(找了好久....) 歌曲歌词获取 ,不过好多好听的歌曲居然播放不了,你懂得,大天朝版权问题....找一首歌,播放就能看到看到歌词了。关于歌词,有许多格式,这里我用的是lrc格式,应该还算比较主流,格式大概如下


[ti:老人与海]
[ar:海鸣威 ]
[al:单曲]
[by:www.5nd.com From 那时花开]
[00:04.08]老人与海 海鸣威
[00:08.78]海鸣威
[00:37.06]秋天的夜凋零在漫天落叶里面
[00:42.43]泛黄世界一点一点随风而渐远
[00:47.58]冬天的雪白色了你我的情人节
[00:53.24]消失不见 爱的碎片
[00:57.87]Rap:
[00:59.32]翻开尘封的相片
[01:00.87]想起和你看过 的那些老旧默片
[01:02.50]老人与海的情节
[01:04.23]画面中你却依稀 在浮现

在有了格式后,我们就需要一个模型,来分离歌曲信息了,下面是我建的模型


#import @interface GLMusicLRCModel : NSObject
//该段歌词对应的时间
@property (nonatomic,assign) NSTimeInterval time;
//歌词
@property (nonatomic,strong) NSString *title;
/**
 *
 将特点的歌词格式进行转换
 *
 **/
+ (id)musicLRCWithString:(NSString *)string;
/**
 *
 根据歌词的路径返回歌词模型数组
 *
 **/
+ (NSArray *)musicLRCModelsWithLRCFileName:(NSString *)name;
@end

#import "GLMusicLRCModel.h"
@implementation GLMusicLRCModel
+(id)musicLRCWithString:(NSString *)string
{
  GLMusicLRCModel *model = [[GLMusicLRCModel alloc] init];
  NSArray *lrcLines =[string componentsSeparatedByString:@"]"];
  if (lrcLines.count == 2) {
    model.title = lrcLines[1];
    NSString *timeString = lrcLines[0];
    timeString = [timeString stringByReplacingOccurrencesOfString:@"[" withString:@""];
    timeString = [timeString stringByReplacingOccurrencesOfString:@"]" withString:@""];
    NSArray *times = [timeString componentsSeparatedByString:@":"];
    if (times.count == 2) {
      NSTimeInterval time = [times[0] integerValue]*60 + [times[1] floatValue];
      model.time = time;
    }
  }else if(lrcLines.count == 1){
    
  }
  
  return model;
}
+(NSArray *)musicLRCModelsWithLRCFileName:(NSString *)name
{
  NSString *lrcPath = [[NSBundle mainBundle] pathForResource:name ofType:nil];
  NSString *lrcString = [NSString stringWithContentsOfFile:lrcPath encoding:NSUTF8StringEncoding error:nil];
  NSArray *lrcLines = [lrcString componentsSeparatedByString:@"n"];
  NSMutableArray *lrcModels = [NSMutableArray array];
  for (NSString *lrcLineString in lrcLines) {
    if ([lrcLineString hasPrefix:@"[ti"] || [lrcLineString hasPrefix:@"[ar"] || [lrcLineString hasPrefix:@"[al"] || ![lrcLineString hasPrefix:@"["]) {
      continue;
    }
    GLMusicLRCModel *lrcModel = [GLMusicLRCModel musicLRCWithString:lrcLineString];
    [lrcModels addObject:lrcModel];
  }
  return lrcModels;
}
@end