我有一个AVAudioEngine设置,AVAudioPlayerNode播放一些背景音乐。
我正在尝试找到一种在2秒钟内在节点上创建音量淡出的最佳方法。我正在考虑使用CADisplayLink来做到这一点。我想知道是否有人有这种情况的经验,可以告诉我他们的方法吗?
答案 0 :(得分:2)
您可以在均衡器中使用全局增益。
例如
AVAudioUnitEQ *Volume;
Volume = [[AVAudioUnitEQ alloc] init];
[engine attachNode:Volume];
[engine connect:Volume to:engine.outputNode format:nil];
然后
Volume.globalGain = /*here your floatValue*/
答案 1 :(得分:1)
我的方法如下。请注意,我将计时器分配给成员var,以便我可以在其他点(viewWillDisappear
,delloc
等)使其无效。我担心听起来不会很顺利,但是我尝试了它并且工作正常,不需要使用CADisplayLink
。
- (void)fadeOutAudioWithDuration:(double)duration {
double timerInterval = 0.1;
NSNumber *volumeInterval = [NSNumber numberWithDouble:(timerInterval / duration)];
self.fadeOutTimer = [NSTimer scheduledTimerWithTimeInterval:timerInterval target:self selector:@selector(fadeOutTimerDidFire:) userInfo:volumeInterval repeats:YES];
}
- (void)fadeOutTimerDidFire:(NSTimer *)timer {
float volumeInterval = ((NSNumber *)timer.userInfo).floatValue;
float currentVolume = self.audioEngine.mainMixerNode.outputVolume;
float newValue = MAX(currentVolume - volumeInterval, 0.0f);
self.audioEngine.mainMixerNode.outputVolume = newValue;
if (newValue == 0.0f) {
[timer invalidate];
}
}
答案 2 :(得分:0)
如果像我这样的人还在寻找答案:
从文档来看,AVAudioPlayerNode 不支持音量属性,只有 AVAudioMixerNode 节点支持。因此,请确保将 AVAudioPlayerNode 封装到 AVAudioMixerNode 中。
这是一个用于淡入、淡出和淡入淡出的代码(Swift 5)
typealias Completion = (() -> Void)
let mixer = AVAudioMixerNode()
func fade(from: Float, to: Float, duration: TimeInterval, completion: Completion?) {
let stepTime = 0.01
let times = duration / stepTime
let step = (to - from) / Float(times)
for i in 0...Int(times) {
DispatchQueue.main.asyncAfter(deadline: .now() + Double(i) * stepTime) {
mixer.volume = from + Float(i) * step
if i == Int(times) {
completion?()
}
}
}
}
func fadeIn(duration: TimeInterval = 1.3, completion: Completion? = nil) {
fade(from: 0, to: 1, duration: duration, completion: completion)
}
func fadeOut(duration: TimeInterval = 1.3, completion: Completion? = nil) {
fade(from: 1, to: 0, duration: duration, completion: completion)
}