// The ringback heard while the other phone rings: the North American tone// (440 Hz with 480 Hz, two seconds on and four off), made here rather than// shipped as a file. It plays on the call's audio session, which CallKit has// activated by the time the core says `play_tone`.#if os(iOS)import AVFoundation@MainActorpublicfinalclassRingbackTone: CallTonePort {privatevar engine: AVAudioEngine?privatevar player: AVAudioPlayerNode?publicinit() {}publicfunc play(_ tone: String) { stop()let engine = AVAudioEngine()let player = AVAudioPlayerNode()let format = AVAudioFormat(standardFormatWithSampleRate: 44_100, channels: 1)!guardlet cycle = Self.cycle(format: format) else { return } engine.attach(player) engine.connect(player, to: engine.mainMixerNode, format: format)do {try engine.start() } catch {return } player.scheduleBuffer(cycle, at: nil, options: .loops) player.volume = 0.25 player.play()self.engine = engineself.player = player }publicfunc stop() { player?.stop() engine?.stop() player = nil engine = nil }/// One six-second cycle: two seconds of the two tones, four of silence.privatestaticfunc cycle(format: AVAudioFormat) -> AVAudioPCMBuffer? {let rate = format.sampleRatelet frames = AVAudioFrameCount(rate * 6)guardlet buffer = AVAudioPCMBuffer(pcmFormat: format, frameCapacity: frames), let samples = buffer.floatChannelData?[0] else { returnnil } buffer.frameLength = frameslet on = Int(rate * 2)for frame in0..<Int(frames) {guard frame < on else { samples[frame] = 0continue }let time = Double(frame) / rate// A few milliseconds of fade at each edge, so the tone does not click.let edge = min(1, Double(min(frame, on - frame)) / (rate * 0.01)) samples[frame] = Float((sin(2 * .pi * 440 * time) + sin(2 * .pi * 480 * time)) * 0.5 * edge) }return buffer }}#endif