我正在尝试使用AVAudioEngine在音频上应用效果。为此,我执行了以下操作:
func playAudioWithVariablePitch(pitch:Float){
audioPlayer.stop()
audioEngine.stop()
audioEngine.reset()
audioPlayerNode = AVAudioPlayerNode()
audioEngine.attach(audioPlayerNode)
let changePitchEffect = AVAudioUnitTimePitch()
changePitchEffect.pitch = pitch
audioEngine.attach(changePitchEffect)
audioEngine.connect(audioPlayerNode, to:changePitchEffect, format:nil)
audioEngine.connect(changePitchEffect, to:audioEngine.outputNode, format:nil)
audioPlayerNode.scheduleFile(audioFile , at:nil, completionHandler:nil)
do{
try audioEngine.start()
audioPlayerNode.play()
}catch{
print("error")
}
}
我正在尝试使用以下代码保存此音频:
//---saving task has to be done ----//
let dirPaths: AnyObject = NSSearchPathForDirectoriesInDomains( FileManager.SearchPathDirectory.documentDirectory, FileManager.SearchPathDomainMask.userDomainMask, true)[0] as AnyObject
let tmpFileUrl: NSURL = NSURL.fileURL(withPath: dirPaths.appendingPathComponent("effectedSound2.m4a")) as NSURL
let filteredOutputURL = tmpFileUrl
do{
print(dirPaths)
let newAudio = try! AVAudioFile(forWriting: tmpFileUrl as URL, settings: [
AVFormatIDKey: NSNumber(value:kAudioFormatAppleLossless),
AVEncoderAudioQualityKey : AVAudioQuality.low.rawValue,
AVEncoderBitRateKey : 320000,
AVNumberOfChannelsKey: 2,
AVSampleRateKey : 44100.0
])
let length = self.audioFile.length
audioEngine.mainMixerNode.installTap(onBus: 0, bufferSize: 1024, format: self.audioEngine.mainMixerNode.inputFormat(forBus: 0)) {
(buffer: AVAudioPCMBuffer!, time: AVAudioTime!) -> Void in
print(newAudio.length)
print("=====================")
print(length)
print("**************************")
if (newAudio.length) < length {//Let us know when to stop saving the file, otherwise saving infinitely
do{
//print(buffer)
try newAudio.write(from: buffer)
}catch _{
print("Problem Writing Buffer")
}
}else{
self.audioEngine.mainMixerNode.removeTap(onBus: 0)//if we dont remove it, will keep on tapping infinitely
//DO WHAT YOU WANT TO DO HERE WITH EFFECTED AUDIO
}
}
}catch _{
print("Problem")
}
//------saving ends ------//
在保存此效果的同时,我得到了
由于未捕获的异常'com.apple.coreaudio.avfaudio'而终止应用程序,原因:'所需条件为假:!destNodeMixerConns.empty()&&!isDestNodeConnectedToIONode