0

我正在尝试使用 AVAudioEngine 和 AVAudioPlayerNode 淡出 mp3 文件。我想不明白。任何人都可以在 Swift 中提供帮助吗?

我已经尝试了一些东西。一切都很好,但没有我想要的那么顺利。

    var fadeOutPlayer: Float = playerVolume
            var fadeOutQuinte: Float = playerQuinteVolume
            while fadeOutPlayer > 0.0 {
                player.volume = fadeOutPlayer
                playerQuinte.volume = fadeOutQuinte
                fadeOutPlayer -= 0.001
                fadeOutQuinte -= 0.001
                usleep(100)
            }


我还尝试了一个计时器(它不会褪色):

if !isTimerFadeOutRunning {
            player.volume = 0
            playerQuinte.volume = 0
            counter = 0
            timerFadeOut = Timer.scheduledTimer(timeInterval: 0.1, target: self, selector: #selector(runTimerFadeOut), userInfo: nil, repeats: true)
            isTimerFadeOutRunning = true
        }
    }

    @objc func runTimerFadeOut() {
        counter += 0.1
        if counter == 0.2 {
            player.pause()
            playerQuinte.pause()
        }
    }
4

1 回答 1

0

我在 mainMixerNode 之前将一个 AVAudioUnitEQ 附加到我的流中,然后控制 globalGain。下面的代码展示了这个想法:

private func manageFadeOut(volume: Double, fadeOutSecs: Double) {
    let timeSecs = 0.001
    DispatchQueue.main.asyncAfter(deadline: .now() + timeSecs) {
        if !self.isFadingOut { return }
        for fx in self.fadeOutEffects { fx.globalGain = Float(-96 * (1.0 - volume)) }
        if volume <= 0 {
            for player in self.players { player.stop() }
            self.isFadingOut = false
            return
        }
        let fade = timeSecs / fadeOutSecs
        self.manageFadeOut(volume: volume - fade, fadeOutSecs: fadeOutSecs)
    }
}
于 2020-09-21T12:47:46.543 回答