使用AVAudioEngine淡入/淡出

时间:2016-04-18 17:00:18

标签: avaudioengine

我的应用动态添加和删除提供setState()的节点。发生这种情况时,我会听到咔嗒声或砰砰声,因为音量没有消失。

如何在进行连接时实现平滑过渡?我是否需要在我的AudioUnit中实现淡入淡出或者AVAudioEngine能够更优雅地处理它?<​​/ p>

1 个答案:

答案 0 :(得分:1)

我在我的应用程序中淡出而没有触及AudioUnit(代码如下)。 你也可以通过调整来淡化。

请注意,我将计时器分配给成员var,以便我可以在其他点(viewWillDisappeardelloc等)使其无效。我担心它听起来不会很平滑,但我尝试过它并且工作正常。

- (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];
    }
}