Skip to content

Instantly share code, notes, and snippets.

@akio0911
Created November 26, 2020 08:06
Show Gist options
  • Save akio0911/e3a67471011f3ac2049561d1b2585520 to your computer and use it in GitHub Desktop.
Save akio0911/e3a67471011f3ac2049561d1b2585520 to your computer and use it in GitHub Desktop.
import UIKit
import AVFoundation
// [iOS]ボイスレコーダーアプリを作る - Qiita
// https://qiita.com/army_sh/items/946aa15263a6d087a99c
class ViewController: UIViewController {
private enum State {
case idle
case recording
case playing
}
@IBOutlet weak var statusLabel: UILabel!
@IBOutlet weak var recordButton: UIButton!
@IBOutlet weak var playButton: UIButton!
var audioRecorder: AVAudioRecorder!
var audioPlayer: AVAudioPlayer!
private var status: State = .idle
@IBAction func didTapRecordButton(_ sender: Any) {
switch status {
case .idle:
let session = AVAudioSession.sharedInstance()
try! session.setCategory(.playAndRecord)
try! session.setActive(true)
let settings = [
AVFormatIDKey: Int(kAudioFormatMPEG4AAC),
AVSampleRateKey: 44100,
AVNumberOfChannelsKey: 2,
AVEncoderAudioQualityKey: AVAudioQuality.high.rawValue
]
audioRecorder = try! AVAudioRecorder(url: getURL(), settings: settings)
audioRecorder.delegate = self
audioRecorder.record()
status = .recording
case .recording:
audioRecorder.stop()
status = .idle
case .playing:
break
}
updateUI()
}
private func getURL() -> URL {
let paths = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask)
let docsDirect = paths[0]
return docsDirect.appendingPathComponent("recording.m4a")
}
@IBAction func didTapPlayButton(_ sender: Any) {
switch status {
case .idle:
audioPlayer = try! AVAudioPlayer(contentsOf: getURL())
audioPlayer.delegate = self
audioPlayer.play()
status = .playing
case .playing:
audioPlayer.stop()
status = .idle
case .recording:
break
}
updateUI()
}
private func updateUI() {
statusLabel.text = {
switch status {
case .idle:
return "待機中"
case .recording:
return "録音中"
case .playing:
return "再生中"
}
}()
recordButton.setTitle(
{
switch status {
case .idle, .playing:
return "RECORD"
case .recording:
return "STOP"
}
}(),
for: .normal
)
recordButton.isEnabled = {
switch status {
case .idle, .recording:
return true
case .playing:
return false
}
}()
playButton.setTitle(
{
switch status {
case .idle, .recording:
return "PLAY"
case .playing:
return "STOP"
}
}(),
for: .normal
)
playButton.isEnabled = {
switch status {
case .idle, .playing:
return true
case .recording:
return false
}
}()
}
}
extension ViewController: AVAudioRecorderDelegate {
}
extension ViewController: AVAudioPlayerDelegate {
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment