Component:
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