iT邦幫忙

2018 iT 邦幫忙鐵人賽
DAY 15
1
Software Development

30天Swift入門學習系列 第 15

iOS App 實作(12)錄音功能(AVAudioRecorder)


Description:
上一篇寫了聲音播放功能,這篇就來介紹如何錄音吧。
此demo提供一可錄音之按鈕,錄完的音訊會於下方列表中顯示。

Component:

  1. AVAudioRecorder
  2. AVAudioPlayer
  3. UITableView

Highlight function:
首先先使用iOS UserDefaults 來建立檔案名稱:

var numOfRecorder: Int = 0

if let number: Int = UserDefaults.standard.object(forKey: "myNumber") as? Int {
  numOfRecorder = number
}

利用上述建立好的檔名來新增檔案:

let destinationUrl = getDirectoryPath().appendingPathComponent("\(numOfRecorder).m4a")

在錄音時,須先設定錄音的在錄音時,須先設定錄音的檔案格式及音質:

let settings = [AVFormatIDKey: Int(kAudioFormatMPEG4AAC),
                AVSampleRateKey: 44100,
                AVNumberOfChannelsKey: 2,
                AVEncoderAudioQualityKey: AVAudioQuality.high.rawValue
               ]

AVAudioRecorder 開始錄音及停止的方法,跟 AVAudioPlayer 很相似:

audioRecorder.record()
audioRecorder.stop()

完整的錄音實作:

  @IBAction func recordBtnAction() {
    if audioRecorder == nil {
      numOfRecorder += 1
      
      let destinationUrl = getDirectoryPath().appendingPathComponent("\(numOfRecorder).m4a")
     
      let settings = [AVFormatIDKey: Int(kAudioFormatMPEG4AAC),
                      AVSampleRateKey: 44100,
                      AVNumberOfChannelsKey: 2,
                      AVEncoderAudioQualityKey: AVAudioQuality.high.rawValue
                     ]
      
      do {
        audioRecorder = try AVAudioRecorder(url: destinationUrl, settings: settings)
        audioRecorder.record()
        
        recordBtn.setTitle("Stop", for: .normal)
      } catch {
        print("Record error:", error.localizedDescription)
      }
    } else {
      audioRecorder.stop()
      audioRecorder = nil
      
      // save file name of record data in tableview
      UserDefaults.standard.set(numOfRecorder, forKey: "myNumber")
      tableView.reloadData()
      
      recordBtn.setTitle("Record", for: .normal)
    }
  }

Additional:
在錄音時需要跟使用者要求麥克風的使用權限,需先在 plist.info 中加入權限要求:

另外, iOS 預設是不允許 app 使用麥克風這 hardware ,因此在使用前須先改變 AVAudioSession 的設定

recordingSession.setCategory(AVAudioSessionCategoryPlayAndRecord)

Reference:
Source code on Github


上一篇
iOS App 實作(11)音樂播放(AVAudioPlayer)
下一篇
淺談AVAudioSession
系列文
30天Swift入門學習30
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言