开篇
播放音频的效果图:
效果图需求分析
- 灰色波形底图
- 播放过程,白色波形覆盖
实现思路
灰色波形底图是固定的,可直接用图层绘制
1、波形的路径计算与上篇类似
//波形路径
- (CGPathRef)pathWithPoints:(NSArray *)points{
CGFloat midY = NSHeight(self.bounds) / 2.f;
CGFloat leftX = NSMaxX(playBtnRect);
CGMutablePathRef wavePath = CGPathCreateMutable(); //绘制路径
CGPathMoveToPoint(wavePath, nil, leftX, midY);
for (NSInteger i = 0; i < _pointArray.count; i++) {
NSValue *pointValue = _pointArray[i];
NSPoint point = pointValue.pointValue;
if (point.y == 0) {
CGPathMoveToPoint(wavePath, nil, leftX + i - 1, midY);
CGPathAddLineToPoint(wavePath, NULL, leftX + i, midY);
}else{
CGPathMoveToPoint(wavePath, nil, leftX + i, midY);
CGPathAddLineToPoint(wavePath, NULL, leftX + i, midY + point.y);
CGPathMoveToPoint(wavePath, nil, leftX + i, midY);
CGPathAddLineToPoint(wavePath, NULL, leftX + i, midY - point.y);
}
}
CGPathRef path = CGPathCreateCopy(wavePath);
CGPathRelease(wavePath);
return path;
}
绘制灰色波形
//添加完整波形图层
- (void)addWaveLayerWithPath:(CGPathRef)wavePath{
CAShapeLayer *shapeLayer = [CAShapeLayer layer];
shapeLayer.lineWidth=1;
shapeLayer.strokeColor=[NSColor lightGrayColor].CGColor;
shapeLayer.lineCap = kCALineCapRound;
shapeLayer.lineJoin = kCALineJoinRound;
[self.layer addSublayer:shapeLayer];
shapeLayer.path = wavePath;
}
2、播放图层,使用CAShapeLayer
实现,CAShapeLayer
是唯一一个可动画效果的图层了
//添加播放动画图层
- (void)addAnimationLayerWithPath:(CGPathRef)path{
animationLayer = [CAShapeLayer layer];
animationLayer.path = path;
animationLayer.lineWidth = 1;
animationLayer.strokeColor=[NSColor whiteColor].CGColor;
animationLayer.lineCap = kCALineCapRound;
animationLayer.lineJoin = kCALineJoinRound;
[self.layer addSublayer:animationLayer];
animationLayer.speed = 0; //禁止动画执行
animation = [CABasicAnimation animationWithKeyPath:@"strokeEnd"];
animation.duration = _playDuration;
animation.fromValue = @(0.0f);
animation.toValue = @(1.0f);
animation.delegate = self;
[animationLayer addAnimation:animation forKey:@""];
}
animationLayer.speed
设为0,即动画速度为0,也就是不执行。
@"strokeEnd"
是路径的结束点,始于0,止于1,当动画开始执行,就能看到绘制过程了。
3、播放的开始、暂停、继续、停止
对动画的控制,主要是对speed
、timeOffset
、beginTime
等属性的设置。
- (void)play{
[self resume];
}
- (void)pause{
_playing = NO;
[self setNeedsDisplay:YES];
CFTimeInterval pausedTime = [animationLayer convertTime:CACurrentMediaTime() fromLayer:nil];
animationLayer.speed = 0;
animationLayer.timeOffset = pausedTime;
}
- (void)resume{
_playing = YES;
[self setNeedsDisplay:YES];
CFTimeInterval pausedTime = [animationLayer timeOffset];
animationLayer.speed = 1.0;
animationLayer.timeOffset = 0.0;
animationLayer.beginTime = 0;
CFTimeInterval timeSincePause = [animationLayer convertTime:CACurrentMediaTime() fromLayer:nil] - pausedTime;
animationLayer.beginTime = timeSincePause;
}
- (void)stop{
_playing = NO;
[self setNeedsDisplay:YES];
animationLayer.timeOffset = 0;
animationLayer.speed = 0;
//动画播放完成后,默认自动removed
[animationLayer addAnimation:animation forKey:@""];
}
Demo 地址:https://github.com/YunFei2015/AudioWaveAnimation.git
网友评论