Last active
June 4, 2018 03:28
-
-
Save yungookim/5a78cdf8254a026ad13e713725c7abd8 to your computer and use it in GitHub Desktop.
This file contains hidden or 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 | |
import QuartzCore | |
public class Recording : NSObject, AVAudioRecorderDelegate { | |
@objc public enum State: Int { | |
case None, Record, Play | |
} | |
static var directory: String { | |
return NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true)[0] | |
} | |
public private(set) var url: NSURL | |
public var bitRate = 192000 | |
public var sampleRate = 44100.0 | |
public var channels = 1 | |
private var recorder: AVAudioRecorder? | |
private var player: AVAudioPlayer? | |
private var filename = "foo.m4a" | |
// MARK: - Initializers | |
private init() { | |
url = NSURL(fileURLWithPath: Recording.directory).appendingPathComponent(filename)! as NSURL | |
} | |
// MARK: - Record | |
private func prepare() throws { | |
let settings: [String: AnyObject] = [ | |
AVFormatIDKey : NSNumber(value: Int32(kAudioFormatMPEG4AAC)), | |
// Change below to any quality your app requires | |
AVEncoderAudioQualityKey: AVAudioQuality.medium.rawValue as AnyObject, | |
AVEncoderBitRateKey: bitRate as AnyObject, | |
AVNumberOfChannelsKey: channels as AnyObject, | |
AVSampleRateKey: sampleRate as AnyObject | |
] | |
recorder = try AVAudioRecorder(url: url as URL, settings: settings) | |
recorder?.delegate = self | |
recorder?.prepareToRecord() | |
} | |
public func record() throws { | |
print("Saving to \(url)") | |
if recorder == nil { | |
try prepare() | |
} | |
recorder?.record() | |
state = .Record | |
} | |
// MARK: - Playback | |
public func play() throws { | |
player = try AVAudioPlayer(contentsOf: url as URL) | |
player?.volume = 1.0 | |
player?.play() | |
state = .Play | |
} | |
public func stop() { | |
switch state { | |
case .Play: | |
player?.stop() | |
player = nil | |
case .Record: | |
recorder?.stop() | |
recorder = nil | |
default: | |
break | |
} | |
state = .None | |
} | |
// MARK: - Delegates | |
public func audioRecorderDidFinishRecording(_ recorder: AVAudioRecorder, successfully flag: Bool) { | |
print("audioRecorderDidFinishRecording") | |
} | |
public func audioRecorderEncodeErrorDidOccur(_ recorder: AVAudioRecorder, error: Error?) { | |
print("audioRecorderEncodeErrorDidOccur \(String(describing: error?.localizedDescription))") | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment