Skip to content

Instantly share code, notes, and snippets.

@tion-low
Created August 20, 2019 06:28
Show Gist options
  • Save tion-low/8b433dd83bec67ea8efc808a3d7e3607 to your computer and use it in GitHub Desktop.
Save tion-low/8b433dd83bec67ea8efc808a3d7e3607 to your computer and use it in GitHub Desktop.
import UIKit
import AVFoundation
let engine = AVAudioEngine()
let player = AVAudioPlayerNode()
let mixer1 = AVAudioMixerNode()
let mixer2 = AVAudioMixerNode()
engine.attach(player)
engine.attach(mixer1)
engine.attach(mixer2)
engine.connect(player, to: [
AVAudioConnectionPoint(node: mixer1, bus: 0),
AVAudioConnectionPoint(node: mixer2, bus: 0)
], fromBus: 0, format: player.outputFormat(forBus: 0))
engine.connect(mixer1, to: engine.mainMixerNode, format: mixer1.outputFormat(forBus: 0))
engine.connect(mixer2, to: engine.mainMixerNode, format: mixer2.outputFormat(forBus: 0))
try! engine.start()
player.play()
let format = player.outputFormat(forBus: 0)
let sampleRate = format.sampleRate
var buf = AVAudioPCMBuffer(pcmFormat: format, frameCapacity: AVAudioFrameCount(sampleRate))!
buf.frameLength = AVAudioFrameCount(sampleRate)
for ch in 0..<format.channelCount {
let samples = buf.floatChannelData![Int(ch)]
for n in 0..<buf.frameLength {
samples[Int(n)] = sinf(Float(2.0 * Double.pi) * 440.0 * Float(n) / Float(sampleRate))
}
}
player.scheduleBuffer(buf) {
print("complete")
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment