LAST CHANCE: Save 50% on all my Swift books and bundles! >>

Observing AVAudioPlayer volume ramp during fade

Forums > macOS

I am messing around with an app project in which I am trying to implement the scan function of a car radio that scans each channel for a determinate number of seconds, and if there's no interaction the scan method jumps to the next radio station. But, I am doing this with the iTunes library and scanning the tracks of a selected playlist. The app fades in and plays a determinate amount of the track at a specified offset point, such as 20 seconds into the track (to avoid the intro music), for a set number of seconds (10 seconds is used for testing).

The track is faded in using the AVAudioPlayer.setVolume(_ :fadeDuration:) method and then either when the track reaches completion it starts the next track, or if the user clicks the next track button it goes to the next track.

The problem I am having is the fade does not occur because AVAudioPlayer.setVolume method immediately sets the volume to zero, but still performs a ramp within the method and a subsequent call to AVAudioPlayer.stop() method abruptly stops the track with no fade out.

Unfortunately I've not been able to figure out how to observe the ramp and then use the AVAudioPlayer.stop() method once the fade out is complete. I suppose I could set a timer to the fadeOut property value, but I was wondering if there is a way to observe that volume ramp with something like:

fading = AVAudioPlayer.fadeRamp // Bool
while fading {
    fading = AVAudioPlayer.fadeRamp

I asked this question on StackOverflow, but haven't received any responses.

I found an old blog post that implemented something like this using Objective-C back in 2011, but I know nothing about Objective-C, or how to implement that code in a Swiftly manner to create a pointer to the fade ramp, which is what I think that code is doing.

Any thoughts on how I could implement this either directly or by extending the AVAudioPlayer, or should I just implement a timer to handle this?


Hacking with Swift is sponsored by Essential Developer.

SPONSORED Join a FREE crash course for mid/senior iOS devs who want to achieve an expert level of technical and practical skills – it’s the fast track to being a complete senior developer! Hurry up because it'll be available only until July 28th.

Click to save your free spot now

Sponsor Hacking with Swift and reach the world's largest Swift community!

Archived topic

This topic has been closed due to inactivity, so you can't reply. Please create a new topic if you need to.

All interactions here are governed by our code of conduct.

Unknown user

You are not logged in

Log in or create account

Link copied to your pasteboard.