-
-
Save dreamwieber/455c2f2073139bd591f6 to your computer and use it in GitHub Desktop.
AVAudioFile
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import AVFoundation | |
private let _singletonInstance = AudioController() | |
class AudioController { | |
class var sharedInstance: AudioController { | |
return _singletonInstance | |
} | |
let audioEngine: AVAudioEngine = AVAudioEngine() | |
let input: AVAudioInputNode | |
let output: AVAudioOutputNode | |
let inputFormat: AVAudioFormat | |
var isMonitoring: Bool | |
var isRecording: Bool | |
var audioFile: AVAudioFile! | |
init() { | |
input = audioEngine.inputNode | |
output = audioEngine.outputNode | |
inputFormat = input.inputFormatForBus(0) | |
isMonitoring = false | |
isRecording = false | |
} | |
func monitorInput() -> NSError? { | |
if (audioEngine.running) { | |
audioEngine.pause() | |
} | |
audioEngine.connect(input, to: output, format: inputFormat) | |
var error: NSError? | |
audioEngine.startAndReturnError(&error) | |
if error == nil { | |
isMonitoring = true | |
} else { | |
isMonitoring = false | |
} | |
return error | |
} | |
func stopMonitoringInput() -> NSError? { | |
if (audioEngine.running) { | |
audioEngine.pause() | |
} | |
audioEngine.disconnectNodeOutput(input) | |
var error: NSError? | |
audioEngine.startAndReturnError(&error) | |
if error == nil { | |
isMonitoring = false | |
} else { | |
isMonitoring = true | |
} | |
return error | |
} | |
func startRecording() { | |
let url = fileUtilDocumentsDirectoryURLWithFilename("test.aiff") | |
let settings = | |
[AVFormatIDKey: kAudioFormatLinearPCM, | |
AVSampleRateKey: inputFormat.sampleRate, | |
AVNumberOfChannelsKey: 2, | |
AVLinearPCMBitDepthKey : 32, | |
AVLinearPCMIsBigEndianKey : false, | |
AVLinearPCMIsFloatKey : true, | |
AVLinearPCMIsNonInterleaved : false]; | |
var error : NSError? | |
self.audioFile = AVAudioFile(forWriting: url, settings: settings, commonFormat: AVAudioCommonFormat.PCMFormatFloat32, interleaved: false, error: &error) | |
if (error != nil) { | |
println(String(format: "error creating audio file %@", error!)) | |
return | |
} | |
println("recording to file: " + url!.absoluteString!) | |
input.installTapOnBus(0, bufferSize: 4096, format: nil) { (buffer, when) -> Void in | |
var writeError: NSError? | |
self.audioFile.writeFromBuffer(buffer, error: &writeError) | |
} | |
isRecording = true | |
} | |
func stopRecording() { | |
input.removeTapOnBus(0) | |
isRecording = false | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment