美文网首页
从视频中提取wav格式的音频

从视频中提取wav格式的音频

作者: 异乡人_4f2a | 来源:发表于2023-11-22 16:54 被阅读0次
        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格式的音频

      本文链接:https://www.haomeiwen.com/subject/aqcwwdtx.html