// 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 @MainActor public final class RingbackTone: CallTonePort { private var engine: AVAudioEngine? private var player: AVAudioPlayerNode? public init() {} public func play(_ tone: String) { stop() let engine = AVAudioEngine() let player = AVAudioPlayerNode() let format = AVAudioFormat(standardFormatWithSampleRate: 44_100, channels: 1)! guard let 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 = engine self.player = player } public func stop() { player?.stop() engine?.stop() player = nil engine = nil } /// One six-second cycle: two seconds of the two tones, four of silence. private static func cycle(format: AVAudioFormat) -> AVAudioPCMBuffer? { let rate = format.sampleRate let frames = AVAudioFrameCount(rate * 6) guard let buffer = AVAudioPCMBuffer(pcmFormat: format, frameCapacity: frames), let samples = buffer.floatChannelData?[0] else { return nil } buffer.frameLength = frames let on = Int(rate * 2) for frame in 0..