guard let lastPathComponent = resourceModel?.path.deletingPathExtension.lastPathComponent else { return }
let resultPath = path.appendingPathComponent(lastPathComponent).appending(".wav")
if fileManager.fileExists(atPath: resultPath) {
do{
try fileManager.removeItem(atPath: resultPath)
}catch{
print(error.localizedDescription)
}
}
let videoAsset = AVAsset(url:URL(fileURLWithPath:resourceModel?.path ?? ""))
let audioTrack = videoAsset.tracks(withMediaType:AVMediaType.audio).first!
let outputFileURL =URL(fileURLWithPath: resultPath)
let assetReader =try! AVAssetReader(asset: videoAsset)
// 配置音频输出设置
let outputSettings: [String:Any] = [
AVFormatIDKey : Int(kAudioFormatLinearPCM),
AVLinearPCMBitDepthKey : 16,
AVLinearPCMIsBigEndianKey : false,
AVLinearPCMIsFloatKey : false,
AVLinearPCMIsNonInterleaved : false,
AVSampleRateKey:16000,
AVNumberOfChannelsKey: 1
]
let output = AVAssetReaderAudioMixOutput(audioTracks: [audioTrack],
audioSettings: outputSettings)
assetReader.add(output)
let assetWriter =try! AVAssetWriter(outputURL: outputFileURL,fileType:AVFileType.wav)
let input = AVAssetWriterInput(mediaType:AVMediaType.audio,outputSettings: outputSettings)
assetWriter.add(input)
assetWriter.startWriting()
assetReader.startReading()
assetWriter.startSession(atSourceTime:CMTime(value:0,timescale:30))
let queue = DispatchQueue(label:"audioextractor")
input.requestMediaDataWhenReady(on: queue) {
while input.isReadyForMoreMediaData&& assetReader.status == .reading{
if let buffer = output.copyNextSampleBuffer() {
input.append(buffer)
} else {
input.markAsFinished()
assetWriter.finishWriting{
// 处理导出完成事件
self.loadVoiceToText(resultPath)
}
break
}
}
}
网友评论