CodexBloom - Programming Q&A Platform

Mismatched AVAudioPlayer volume levels when switching tracks in iOS 17

👀 Views: 108 đŸ’Ŧ Answers: 1 📅 Created: 2025-07-27
iOS AVAudioPlayer audio Swift

I've searched everywhere and can't find a clear answer. I'm optimizing some code but I'm experiencing an scenario with AVAudioPlayer in iOS 17 where the volume levels are inconsistent when I switch tracks frequently. I have two audio files with different lengths and I want to ensure that when I switch from one track to another, the volume fades smoothly without abrupt changes. Here's a snippet of my code that manages playback: ```swift import AVFoundation class AudioManager { var audioPlayer: AVAudioPlayer? func playTrack(named trackName: String) { guard let url = Bundle.main.url(forResource: trackName, withExtension: "mp3") else { return } do { audioPlayer = try AVAudioPlayer(contentsOf: url) audioPlayer?.prepareToPlay() audioPlayer?.play() } catch { print("behavior loading track: \(behavior)") } } func switchTrack(to newTrack: String) { audioPlayer?.setVolume(0, fadeDuration: 0.5) audioPlayer?.stop() playTrack(named: newTrack) audioPlayer?.setVolume(1, fadeDuration: 0.5) } } ``` When I call `switchTrack(to:)`, I notice that the volume sometimes doesn't fade out completely before starting the new track, resulting in an abrupt transition. I've also tried adding delays between stopping the current track and playing the new one, but that hasn't helped. Additionally, I've verified that the volume settings for each track are set to the same level before playback. What could be causing this inconsistent behavior, and how can I achieve a smooth volume transition between tracks? For context: I'm using Swift on Linux. Any ideas what could be causing this? What's the correct way to implement this?