啥也不说先上图。
录音配置代码
private func configRecord() {
AVAudioSession.sharedInstance().requestRecordPermission { (allowed) in
if!allowed {
return
}
}
letsession =AVAudioSession.sharedInstance()
do { try session.setCategory(AVAudioSessionCategoryPlayAndRecord, with: .defaultToSpeaker) }
catch { print("session config failed") }
do{
self.recorder=tryAVAudioRecorder(url:self.directoryURL()!, settings:self.recorderSetting)
self.recorder.delegate=self
self.recorder.prepareToRecord()
self.recorder.isMeteringEnabled=true
}catch{
print(error.localizedDescription)
}
do { try AVAudioSession.sharedInstance().setActive(true) }
catch { print("session active failed") }
}
//配置相关
private func configAVAudioSession() {
letsession =AVAudioSession.sharedInstance()
do { try session.setCategory(AVAudioSessionCategoryPlayAndRecord, with: .defaultToSpeaker) }
catch { print("session config failed") }
}
定时器记录波纹大小
//添加音频数据
private func updateMeters() {
recorder.updateMeters()
recordTime += updateFequency
addSoundMeter(item:recorder.averagePower(forChannel:0))
}
funcamplitude() ->Float{
self.recorder?.updateMeters()
// 以分贝为单位返回指定信道的平均功率
// averagePower 0db:最大功率- 160db:最小功率(几乎无声)
letdecibel =recorder?.averagePower(forChannel:0) ??0
// 从分贝获得振幅
letamp =pow(10, decibel/20)
returnmax(0,min(amp,1))// 0…1之间的值
}
privatefuncaddSoundMeter(item:Float) {
// 从分贝获得振幅
letamp =pow(10, item/20)
soundMeters.append(max(0,min(amp,1)))
}
然后根据得到的数据绘制波形高度。
接下来就是音频的裁剪,直接利用原生的api进行裁剪
func editSaveCenter(
originUrl:URL,// 收录的文件
exportFileUrl:URL,// 编辑后导出的文件
timeRanges: [CMTime],// 删除部分以外的时间范围
fileType:AVFileType= .m4a,//文件类型
completion:@escaping(Result) ->Void
) {
letoriginAsset =AVURLAsset(url: originUrl)
letexportSession =AVAssetExportSession(
asset: originAsset,
presetName:AVAssetExportPresetAppleM4A
)!
exportSession.outputURL= exportFileUrl
exportSession.outputFileType= fileType
exportSession.timeRange=CMTimeRange(start: timeRanges.first??kCMTimeZero, end: timeRanges.last??kCMTimeZero)
exportSession.exportAsynchronously{
switchexportSession.status{
case.completed:
completion(.success(exportFileUrl))
default:
completion(.failure(exportSession.error!))
}
}
}
demo里面还包含音频合成相关代码。
具体demo请查看:https://github.com/cai3804007/EditAudio.git
好用记得给个start