Skip to content

Instantly share code, notes, and snippets.

@dimagimburg
Created May 23, 2017 21:30
Show Gist options
  • Save dimagimburg/54f24b24d08643b177804955483ac878 to your computer and use it in GitHub Desktop.
Save dimagimburg/54f24b24d08643b177804955483ac878 to your computer and use it in GitHub Desktop.
plays sine wav programmatically with swift 3
import UIKit
import AudioKit
import AVFoundation
class ViewController: UIViewController {
var ae:AVAudioEngine?
var player:AVAudioPlayerNode?
var mixer:AVAudioMixerNode?
var buffer:AVAudioPCMBuffer?
override func viewDidLoad() {
super.viewDidLoad()
ae = AVAudioEngine()
player = AVAudioPlayerNode()
mixer = ae?.mainMixerNode;
buffer = AVAudioPCMBuffer(pcmFormat: (player?.outputFormat(forBus: 0))!, frameCapacity: 100)
buffer?.frameLength = 100
// generate sine wave
let sr:Float = Float((mixer?.outputFormat(forBus: 0).sampleRate)!)
let n_channels = mixer?.outputFormat(forBus: 0).channelCount
for i in stride(from:0, to: Int((buffer?.frameLength)!), by: Int(n_channels!)) {
let val = sinf(441.0*Float(i)*2*Float(Double.pi)/sr)
buffer?.floatChannelData?.pointee[i] = val * 0.5
}
// setup audio engine
ae?.attach(player!)
ae?.connect(player!, to: mixer!, format: player?.outputFormat(forBus: 0))
do{
try ae?.start()
} catch {
}
// play player and buffer
player?.play()
player?.scheduleBuffer(buffer!, at: nil, options: .loops, completionHandler: nil)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment