Of course! Here is a clear and complete Swift example demonstrating how to ramp the volume of an AVAudioNode using scheduleParameterRamp.
For this example, we will:
- Set up an
AVAudioEngine.
- Create a sound source using an
AVAudioPlayerNode and a generated tone (so you don't need an audio file).
- Use the engine's
mainMixerNode as the node whose volume we will control. This is a common and robust approach.
- Create a simple class to manage the audio and provide a clean
rampVolume method.
The Code
This code is self-contained. You can paste it into a Swift Playground or a command-line tool project to run it.
import Foundation
import AVFoundation
/// A class to manage an AVAudioEngine, play a continuous tone, and demonstrate volume ramping.
class AudioVolumeRampController {
// MARK: - AVFoundation Properties
private let engine = AVAudioEngine()
private let playerNode = AVAudioPlayerNode()
// We will control the volume of the main mixer, which is a common practice.
private let mixer: AVAudioMixerNode
private var toneBuffer: AVAudioPCMBuffer?
/// A convenience property to get the current volume of the mixer.
var currentVolume: Float {
return mixer.volume
}
// MARK: - Initialization
init() {
// Get the engine's main mixer node. This node is connected to the output by default.
self.mixer = engine.mainMixerNode
// Attach the player node to the engine's processing graph.
engine.attach(playerNode)
// Define the audio format for the connection.
// We'll use the mixer's input format to ensure compatibility.
let mixerFormat = mixer.inputFormat(forBus: 0)
// Connect the player node to the mixer.
// Player -> Mixer -> Output
engine.connect(playerNode, to: mixer, format: mixerFormat)
// Prepare the audio source (a simple sine wave).
prepareToneBuffer()
}
// MARK: - Audio Playback Control
/// Starts the audio engine and begins playing the tone.
func start() {
guard let toneBuffer = toneBuffer else {
print("Error: Audio buffer is not prepared.")
return
}
// Schedule the buffer to play in a loop.
playerNode.scheduleBuffer(toneBuffer, at: nil, options: .loops)
do {
// Start the audio engine. This can throw an error.
try engine.start()
print("✅ Audio engine started.")
// Start the player node.
playerNode.play()
print("🎵 Player node is playing a tone.")
} catch {
print("❌ Could not start audio engine: \(error.localizedDescription)")
}
}
/// Stops the audio engine and playback.
func stop() {
playerNode.stop()
engine.stop()
print("⏹️ Audio engine stopped.")
}
// MARK: - Volume Ramping
/// Schedules a smooth volume change over a specified duration.
///
/// - Parameters:
/// - targetVolume: The final volume level (0.0 to 1.0).
/// - duration: The time in seconds the ramp should take.
func rampVolume(to targetVolume: Float, duration: TimeInterval) {
guard engine.isRunning else {
print("⚠️ Engine is not running. Cannot schedule a ramp. Starting volume directly.")
mixer.volume = targetVolume
return
}
print("🔊 Scheduling volume ramp from \(mixer.volume) to \(targetVolume) over \(duration) seconds...")
// The `scheduleParameterRamp` function smoothly interpolates the parameter's value
// from its current value to the target value.
mixer.volumeRamp(to: targetVolume, duration: duration)
}
// MARK: - Private Helper
/// Creates a 1-second buffer of a 440 Hz sine wave.
private func prepareToneBuffer() {
let sampleRate = 44100.0
let frequency: Float = 440.0 // A4 note
let duration: TimeInterval = 1.0
let frameCount = AVAudioFrameCount(sampleRate * duration)
// Create a standard stereo format.
guard let format = AVAudioFormat(standardFormatWithSampleRate: sampleRate, channels: 2) else { return }
// Create the buffer.
guard let buffer = AVAudioPCMBuffer(pcmFormat: format, frameCapacity: frameCount) else { return }
buffer.frameLength = frameCount
// Get pointers to the left and right channel data.
let leftChannel = buffer.floatChannelData?[0]
let rightChannel = buffer.floatChannelData?[1]
// Calculate the angular frequency.
let angularFrequency = 2 * .pi * frequency
// Fill the buffer with the sine wave.
for frame in 0..<Int(frameCount) {
let time = Float(frame) / Float(sampleRate)
let value = sin(angularFrequency * time) * 0.5 // 0.5 amplitude
leftChannel?[frame] = value
rightChannel?[frame] = value
}
self.toneBuffer = buffer
}
}
// MARK: - AVAudioNode Extension (Convenience)
public extension AVAudioNode {
/// A convenience wrapper for `scheduleParameterRamp` on the `volume` parameter.
///
/// This function handles getting the current time and scheduling the ramp on the audio render thread,
/// ensuring a smooth, immediate transition from the current volume.
///
/// - Parameters:
/// - volume: The target volume to ramp to.
/// - duration: The duration of the ramp in seconds.
func volumeRamp(to volume: Float, duration: TimeInterval) {
// The `installTap` approach to get render time is complex.
// For volume, which is not sample-level critical, using parameter automation is simpler and effective.
// The ramp is scheduled from the *current* value at the time of execution on the render thread.
// A small delay `at: nil` often works well, but for precision, you'd manage AVAudioTime.
self.auAudioUnit.scheduleParameterBlock(100) { (ramp) in // 100ms lookahead
ramp.ramp(toValue: volume, duration: Float(duration))
}
}
}
// MARK: - Example Usage
// To run this in a playground, you need to enable indefinite execution.
#if canImport(PlaygroundSupport)
import PlaygroundSupport
PlaygroundSupport.PlaygroundPage.current.needsIndefiniteExecution = true
#endif
// 1. Create an instance of the controller.
let audioController = AudioVolumeRampController()
// 2. Start the audio playback.
audioController.start()
print("Initial volume is: \(audioController.currentVolume)") // Should be 1.0 (default)
// 3. Schedule a ramp down to silent over 3 seconds.
DispatchQueue.main.asyncAfter(deadline: .now() + 2.0) {
audioController.rampVolume(to: 0.0, duration: 3.0)
}
// 4. After the first ramp finishes, schedule a ramp up to 80% volume over 2 seconds.
DispatchQueue.main.asyncAfter(deadline: .now() + 6.0) { // 2s wait + 3s ramp + 1s silence
audioController.rampVolume(to: 0.8, duration: 2.0)
}
// 5. Finally, stop the audio engine.
DispatchQueue.main.asyncAfter(deadline: .now() + 10.0) {
audioController.stop()
#if canImport(PlaygroundSupport)
PlaygroundSupport.PlaygroundPage.current.finishExecution()
#endif
}
Key Concepts Explained
-
AVAudioEngine Graph: The audio flows from the source (playerNode) to a processing unit (mixer) and then to the output. playerNode -> mixer -> engine.outputNode.
-
AVAudioMixerNode: This is a versatile node for mixing multiple audio streams and applying effects. Crucially, it has a .volume property that can be automated. We use engine.mainMixerNode, which is the default mixer connected to your speakers/headphones.
-
scheduleParameterBlock: This is the modern and recommended way to schedule parameter changes on an AVAudioNode.
- It takes a
lookahead time (how far in the future the audio render thread can look for events).
- The block gives you a
ramp object (AUParameterRamp).
- You call
.ramp(toValue:duration:) on this object. This is a very high-level and easy way to schedule a linear ramp from the parameter's current value to a new one. The audio engine handles all the complex timing and interpolation for you.
-
Convenience Extension: The AVAudioNode.volumeRamp(to:duration:) extension makes the call much cleaner. Instead of dealing with audio units and parameter blocks directly in your main logic, you can just call myNode.volumeRamp(...).
-
DispatchQueue.main.asyncAfter: This is used in the example only to simulate a sequence of events over time. In a real app, you would call audioController.rampVolume(...) in response to user actions (like a button press), game events, or background timers.