録音する

#ソースコード

Swift5に書き換えた
動かしてないけど

```swift
import AVFoundation
import QuartzCore

protocol RecorderDelegate: AVAudioRecorderDelegate {
  func recodDidStart()
  func recodDidStop()
  func soundDidPlay()
  func soundDidStop()
}

extension RecorderDelegate {
  func recodDidStart() {}
  func recodDidStop() {}
  func soundDidPlay() {}
  func soundDidStop() {}
}

final class Recorder: NSObject {

  enum State: Int {
    case none, record, play
  }

  weak var delegate: RecorderDelegate?
  private(set) var filePath: String
  private(set) var fileURL: URL
  private(set) var state: State = .none

  var bitRate = 192000
  var sampleRate = 44100.0
  var channels = 1

  var isRecSound: Bool = true

  fileprivate let session = AVAudioSession.sharedInstance()
  fileprivate var recorder: AVAudioRecorder?
  fileprivate var player: AVAudioPlayer?
  fileprivate var link: CADisplayLink?

  var startTimeInterval: TimeInterval = Date().timeIntervalSince1970
  var maxRec: Double = 60

  private(set) var elapseTime: Double = 0

  // MARK: - Initializers

  init(fileName: String) {
    filePath = "\(NSTemporaryDirectory())\(fileName)"
    fileURL = URL(fileURLWithPath: self.filePath)
  }


  var isAuth: Bool { AVAudioSession.sharedInstance().recordPermission == .granted }

  // MARK: - Record

  func prepare() throws {
    let settings: [String: AnyObject] = [
      AVFormatIDKey : NSNumber(value: Int32(kAudioFormatAppleLossless)),
      AVEncoderAudioQualityKey: AVAudioQuality.max.rawValue as AnyObject,
      AVEncoderBitRateKey: bitRate as AnyObject,
      AVNumberOfChannelsKey: channels as AnyObject,
      AVSampleRateKey: sampleRate as AnyObject
    ]

    unlink(filePath)
    recorder = try AVAudioRecorder(url: fileURL, settings: settings)
    recorder?.prepareToRecord()
    recorder?.delegate = delegate
  }

  func record() throws {

    func main() throws{
      if recorder == nil {
        try prepare()
      }
      try session.setCategory(AVAudioSession.Category.playAndRecord)
      try session.overrideOutputAudioPort(AVAudioSession.PortOverride.speaker)
      recorder?.record()
      state = .record

      link = CADisplayLink(target: self, selector: #selector(update))
      link?.add(to: RunLoop.current, forMode: RunLoop.Mode.common)

      self.startTimeInterval = Date().timeIntervalSince1970
      self.elapseTime = 0

      self.delegate?.recodDidStart()
    }

    if self.isRecSound{
      AudioServicesPlaySystemSound(1113)
      DispatchQueue.main.asyncAfter(deadline: .now() + 0.5, execute: {
        try? main()
      })
    }
    else{
      try main()
    }
  }

  // MARK: - Playback

  func play() throws {
    try session.setCategory(AVAudioSession.Category.playback)

    player = try AVAudioPlayer(contentsOf: fileURL)
    player?.delegate = self
    player?.play()
    state = .play
    self.delegate?.soundDidPlay()
  }

  func stop() {
    switch state {
    case .play:
      player?.stop()
      player = nil
      self.delegate?.soundDidStop()
    case .record:
      recorder?.stop()
      recorder = nil
      self.link?.invalidate()
      self.link = nil
      if self.isRecSound {
        AudioServicesPlaySystemSound(1114)
      }
      self.delegate?.recodDidStop()
    default:
      break
    }

    state = .none
  }

  @objc private func update(_ link: Any) {
    elapseTime = (Date().timeIntervalSince1970 - self.startTimeInterval) as Double
    if elapseTime > maxRec {
      self.stop()
    }
  }
}

extension Recorder: AVAudioPlayerDelegate{
  func audioPlayerDidFinishPlaying(_ player: AVAudioPlayer, successfully flag: Bool) {
    if flag {
      self.stop()
    }
  }
}

```


#ソースコード

swift学びたての3だった頃に書いたやつ
使わなくなったからプロジェクトから削除するけど、いつか使う時にどうせ困るから置いとく

```swift
import AVFoundation
import QuartzCore

@objc public protocol RecorderDelegate: AVAudioRecorderDelegate {
  @objc optional func recodDidStart()
  @objc optional func recodDidStop()
  @objc optional func soundDidPlay()
  @objc optional func soundDidStop()
}

public class Recorder:NSObject{
  
  @objc public enum State: Int {
    case None, Record, Play
  }
  
  public weak var delegate: RecorderDelegate?
  public private(set) var filePath: String
  public private(set) var fileURL: URL
  public private(set) var state: State = .None
  
  public var bitRate = 192000
  public var sampleRate = 44100.0
  public var channels = 1
  
  public var isRecSound:Bool = true
  
  fileprivate let session = AVAudioSession.sharedInstance()
  fileprivate var recorder: AVAudioRecorder?
  fileprivate var player: AVAudioPlayer?
  fileprivate var link: CADisplayLink?
  
  var startTimeInterval:TimeInterval = Date().timeIntervalSince1970
  var maxRec:Double = 60
  
  public fileprivate(set) var elapseTime:Double = 0

  
  // MARK: - Initializers
  
  public init(fileName: String) {
    filePath = "\(NSTemporaryDirectory())\(fileName)"
    fileURL = URL(fileURLWithPath: self.filePath)
  }
  
  
  public func isAuth()->Bool{
    return AVAudioSession.sharedInstance().recordPermission() == .granted
  }
  
  // MARK: - Record
  
  public func prepare() throws {
    let settings: [String: AnyObject] = [
      AVFormatIDKey : NSNumber(value: Int32(kAudioFormatAppleLossless)),
      AVEncoderAudioQualityKey: AVAudioQuality.max.rawValue as AnyObject,
      AVEncoderBitRateKey: bitRate as AnyObject,
      AVNumberOfChannelsKey: channels as AnyObject,
      AVSampleRateKey: sampleRate as AnyObject
    ]
    
    unlink(filePath)
    recorder = try AVAudioRecorder(url: fileURL, settings: settings)
    recorder?.prepareToRecord()
    recorder?.delegate = delegate
  }
  
  public func record() throws {
    
    func main() throws{
      if recorder == nil {
        try prepare()
      }
      try session.setCategory(AVAudioSessionCategoryPlayAndRecord)
      try session.overrideOutputAudioPort(AVAudioSessionPortOverride.speaker)
      recorder?.record()
      state = .Record
      
      link = CADisplayLink(target: self, selector: #selector(update))
      link?.add(to: RunLoop.current, forMode: RunLoopMode.commonModes)
      
      self.startTimeInterval = Date().timeIntervalSince1970
      self.elapseTime = 0
      
      self.delegate?.recodDidStart?()
    }
    
    if self.isRecSound{
      AudioServicesPlaySystemSound(1113)
      DispatchQueue.main.asyncAfter(deadline: .now() + 0.5, execute: {
        try? main()
      })
    }
    else{
      try main()
    }
  }
  
  // MARK: - Playback
  
  public func play() throws {
    try session.setCategory(AVAudioSessionCategoryPlayback)
    
    player = try AVAudioPlayer(contentsOf: fileURL)
    player?.delegate = self
    player?.play()
    state = .Play
    self.delegate?.soundDidPlay?()
  }
  
  public func stop() {
    switch state {
    case .Play:
      player?.stop()
      player = nil
      self.delegate?.soundDidStop?()
    case .Record:
      recorder?.stop()
      recorder = nil
      self.link?.invalidate()
      self.link = nil
      if self.isRecSound{
        AudioServicesPlaySystemSound(1114)
      }
      self.delegate?.recodDidStop?()
    default:
      break
    }
    
    state = .None
  }
  
  
  @objc fileprivate func update(_ link: Any) {
    elapseTime = (Date().timeIntervalSince1970 - self.startTimeInterval) as Double
    if elapseTime > maxRec {
      self.stop()
    }
  }
}

extension Recorder:AVAudioPlayerDelegate{
  
  public func audioPlayerDidFinishPlaying(_ player: AVAudioPlayer, successfully flag: Bool) {
    if flag {
      self.stop()
    }
  }
}

```