Cotton code
63 lines · 2.2 KB · SwiftRaw
// 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@MainActorpublic 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..<Int(frames) {            guard frame < on else {                samples[frame] = 0                continue            }            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