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
}
}
}
从视频中提取wav格式的音频
最后编辑于 :
©著作权归作者所有,转载或内容合作请联系作者
- 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
- 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
- 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
推荐阅读更多精彩内容
- 岁月匆匆不知愁。 每个人的性格,各有不同,这可能是因为受到各自不同的生活环境中的很多种因素的影响,再加上每个人各自...