2
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

VoiceRecorder

Last updated at Posted at 2018-12-23

AVAudioRecorderとAVAudioPlayerへの理解を深めるために作成

ezgif.com-video-to-gif

#ソースコード
RECORDボタンで録音
STOP後にPLAYで再生

ViewController.swift

import UIKit
import AVFoundation

class ViewController: UIViewController,AVAudioRecorderDelegate, AVAudioPlayerDelegate {//レコーダーと再生処理
    
    @IBOutlet var label: UILabel!
    @IBOutlet var recordButton: UIButton!
    @IBOutlet var playButton: UIButton!
    
    var audioRecorder:AVAudioRecorder!//録音
    var audioPlayer:AVAudioPlayer!//再生
    var isRecording = false //録音状態か判別
    var isPlaying = false//再生状態か判別
    
    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view, typically from a nib.
    }

    //録音する処理
    @IBAction func record() {
        if !isRecording {
            
            // 再生と録音の機能をアクティブにする
            let session = AVAudioSession.sharedInstance() //音楽の再生をコントロールすることが可能
            try! AVAudioSession.sharedInstance().setCategory(.playAndRecord, mode: .default, options: [])//チャット用にマイク入力と音声出力を行う際に利用
            try! session.setActive(true) //session時にtryが必要? trueアプリケーションのオーディオセッションを有効にするか false無効にするかを指定します
            
            //録音フォーマットの設定
            let setteings = [
                AVFormatIDKey:Int(kAudioFormatMPEG4AAC),
                AVSampleRateKey: 44100,
                AVNumberOfChannelsKey: 2,
                AVEncoderAudioQualityKey: AVAudioQuality.high.rawValue
            ]
            
            audioRecorder = try! AVAudioRecorder(url: getURL(), settings: setteings)//url記録先のファイルシステムの場所settings録音セッションの設定
            audioRecorder.delegate = self
            
            audioRecorder.record()
            isRecording = true
            
            label.text = "録音中"
            //表示されるテキスト
            recordButton.setTitle("STOP", for: .normal)
            playButton.isEnabled = false
        }else {
            audioRecorder.stop()
            isRecording = false
            
            label.text = "待機中"
            recordButton.setTitle("RECORD", for: .normal)
            playButton.isEnabled = true
        }
    }
    
    
    @IBAction func play() {
        if !isPlaying {
            audioPlayer = try! AVAudioPlayer(contentsOf: getURL())
            audioPlayer.delegate = self
            audioPlayer.play()
            
            isPlaying = true
            
            label.text = "再生中"
            playButton.setTitle("STOP", for: .normal)
            recordButton.isEnabled = false
        }else{
            audioPlayer.stop()
            isPlaying = false
            
            label.text = "待機中"
            playButton.setTitle("PLAY", for: .normal)
            recordButton.isEnabled = true
        }
    }
    
    //再生終了を検知
    func audioPlayerDidFinishPlaying(_ player: AVAudioPlayer, successfully flag: Bool) {
        if flag {
            audioPlayer.stop()
            isPlaying = false
            
            label.text = "待機中"
            playButton.setTitle("PLAY", for: .normal)
            recordButton.isEnabled = true
        }
    }
    
    //ディレクトリのファイルURLを取得
    func getURL() -> URL {
        let paths = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask) //iPhone内のDocumentディレクトリ(ファイル)を探して、そのパスを取得。
        let docsDirect = paths[0]
        let url = docsDirect.appendingPathComponent("recording.m4a") //m4aで保存
        return url
    }
}

#録音フォーマットの設定
info.mDataFormat.mFormatID = kAudioFormatMPEG4AAC
info.mDataFormat.mSampleRate = 44100.0
info.mDataFormat.mChannelsPerFrame = 2
info.mDataFormat.mBitsPerChannel = 0
info.mDataFormat.mFramesPerPacket = 1024
info.mDataFormat.mBytesPerFrame = 0
info.mDataFormat.mBytesPerPacket = 0
info.mDataFormat.mFormatFlags = 0

2
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
2
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?