關(guān)于錄音反正都是調(diào)用系統(tǒng)的東西女轿,沒啥好說的蓉媳,直接上流程
var recorder:AVAudioRecorder? //錄音器
var recorderSeetingsDic:[String : Any]! //錄音器設(shè)置參數(shù)數(shù)組
var volumeTimer:Timer! //定時(shí)器線程岭粤,循環(huán)監(jiān)測錄音的音量大小
var aacPath:String! //錄音存儲(chǔ)路徑
let docDir = NSSearchPathForDirectoriesInDomains(.documentDirectory,
.userDomainMask, true)[0]//獲取手機(jī)根目錄
var musicPlayer = AVAudioPlayer()//播放器
//初始化錄音器
let session:AVAudioSession = AVAudioSession.sharedInstance()
//設(shè)置錄音類型
try! session.setCategory(AVAudioSessionCategoryPlayAndRecord)
//初始化字典并添加設(shè)置參數(shù)
recorderSeetingsDic =
[
AVFormatIDKey: NSNumber(value: kAudioFormatMPEG4AAC),
AVNumberOfChannelsKey: 2, //錄音的聲道數(shù),立體聲為雙聲道
AVEncoderAudioQualityKey : AVAudioQuality.max.rawValue,
AVEncoderBitRateKey : 320000,
AVSampleRateKey : 44100.0 //錄音器每秒采集的錄音樣本數(shù)
]
判斷路徑文件夾是否存在
recordPath = docDir + "/sound"
let fileManager = FileManager.default
//? ? ? ? let exist = fileManager.fileExists(atPath: recordPath)?
let exist = fileManager.fileExists(atPath: recordPath)
if exist == false {
try! fileManager.createDirectory(atPath: recordPath,withIntermediateDirectories: true, attributes: nil)
//? ? ? ? ? ? try! fileManager
}
let currentDate = Date()
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "yyyyMMddHHmmss"
let myStr = dateFormatter.string(from: currentDate)
aacPath = recordPath + "/\(myStr).aac"
print(aacPath)
recorder = try! AVAudioRecorder(url: URL(string: aacPath)!,settings: recorderSeetingsDic!)
if recorder != nil {
//開啟儀表計(jì)數(shù)功能
recorder!.isMeteringEnabled = true
//準(zhǔn)備錄音
recorder!.prepareToRecord()
//開始錄音
recorder!.record()
}
//停止錄音
recorder?.stop()
//錄音器釋放
recorder = nil
//暫停定時(shí)器
volumeTimer.invalidate()
volumeTimer = nil
開始播放
func startPlay() {
if (userDefult.value(forKey: "mySelectBtn") == nil) {
print(myIndex)
userDefult.setValue(myIndex.row, forKey: "mySelectBtn")
playSound()
}else{
linkRow = userDefult.value(forKey: "mySelectBtn") as! Int
if linkRow != myIndex.row {
let myindex :IndexPath = IndexPath(row: linkRow, section: 0)
userDefult.setValue(myIndex.row, forKey: "mySelectBtn")
DispatchQueue.main.async {
let mycell = self.recordTable.cellForRow(at: myindex) as! RecordTableViewCell
mycell.playBtn.isSelected = false
}
}
playSound()
}
}
func playSound(){
let sound = recordPath + "/\(titleArr[myIndex.row])"
//? ? ? ? 播放
print(sound)
player = try! AVAudioPlayer(contentsOf: URL(string: sound)!)
player?.delegate = self
if player == nil {
print("播放失敗")
}else{
player?.volume = 1.0
player?.prepareToPlay()
player?.play()
}
}
暫停播放
func stopPlay(){
if player == nil {
print("停止失敗")
}else{
player?.currentTime = 0
player?.stop()
}
}
//播放完成監(jiān)聽
func audioPlayerDidFinishPlaying(_ player: AVAudioPlayer, successfully flag: Bool) {
print("owari")
let cell = self.recordTable.cellForRow(at: myIndex) as! RecordTableViewCell
cell.playBtn.isSelected = false
}
錄音的使用大致就是這樣实柠,只是還有小部分代碼沒有放上來姥宝,不過基本的流程就是這樣的,等我時(shí)間充裕點(diǎn)再把錄音單獨(dú)從項(xiàng)目里面拿出來其骄。