需求是,几十种音乐可以选择,可以多个同时播放,至多有三种。如果用button做比较简单,但考虑到后期素材更新问题,需要通过服务器下载,使用collectionView对于扩展十分方便,所以选择collectionView.但是也带来许多问题,判断AVAudioPlayer对应的cell,cell的复用导致滑动导致图片排版混乱等等。
AVAudioPlayer对应cell
由于是组合音乐播放,因此创建多个player播放不同音乐,- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath方法中实现,player本身没有类似tag值之类的辨识,也没找到获得当前播放音乐的方法,因此自定义一个AVAudioPlayer,加上一个标志位,用于判断,将点击的cell 的index.row 赋值给标志位,根据标志位,对 对应的音乐进行操作。代码如下
- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath{
//得到点击的cell
UICollectionViewCell * cell = (UICollectionViewCell *)[collectionView cellForItemAtIndexPath:indexPath];
NSString *music_str = [NSString stringWithFormat:@"diyMusic%d",(int)indexPath.row];
if(cell.backgroundColor == [UIColor redColor]){
if (player1 ==nil) {
cell.backgroundColor = [UIColor greenColor];
[self playMusicLoop1:music_str musictype:@"m4a"];
player1.playerFlag = (int)indexPath.row;
}else{
if (player2 ==nil) {
cell.backgroundColor = [UIColor greenColor];
[self playMusicLoop2:music_str musictype:@"m4a"];
player2.playerFlag = (int)indexPath.row;
}else{
if (player3 ==nil) {
cell.backgroundColor = [UIColor greenColor];
[self playMusicLoop3:music_str musictype:@"m4a"];
player3.playerFlag = (int)indexPath.row;
}else{
return;
}
}
}
}else{
if (player1.playerFlag == indexPath.row){
cell.backgroundColor = [UIColor redColor];
player1 = nil;
}
if (player2.playerFlag == indexPath.row){
cell.backgroundColor = [UIColor redColor];
player2 = nil;
}
if (player3.playerFlag == indexPath.row){
cell.backgroundColor = [UIColor redColor];
player3 = nil;
}
}
}
cell复用导致排版混乱
网上看了好多,试了试都不太靠谱,用了最朴实的方法,在cellForItemAtIndexPath中判断自定义的plaer的标志位
if (player1 != nil) {
if (player1.playerFlag==indexPath.row) {
cell.backgroundColor = [UIColor greenColor];
NSLog(@"%d",player1.playerFlag);
}
}
虽然解决的需求,但是方法不太好,不知道有没有更简洁优雅的方法。