我有以下功能:
private func getPCMBuffer(utterance: AVSpeechUtterance,
completion: @escaping (Result<AVAudioPCMBuffer, Failures>) -> Void
) {
speechSynthesizer.write(utterance) { (buffer: AVAudioBuffer) in
guard let pcmBuffer = buffer as? AVAudioPCMBuffer else {
fatalError("unknown buffer type: \(buffer)")
}
completion(.success(pcmBuffer))
}
completion(.failure(.failed))
}
它返回给我一个 AVAudioPCMBuffer。我已经验证了我传入的话语是正确的。
当我尝试将此 AVAudioPCMBuffer 写入本地 URL 时,问题就出现了,如下所示:
getPCMBuffer(utterance: speechUtterance) { result in
switch result {
case .success(let buffer):
var settings: [String : Any] = [:]
let savePathUrl: URL = URL(fileURLWithPath: NSHomeDirectory() + "/Documents/audioFile.caf")
settings[AVFormatIDKey] = kAudioFormatMPEG4AAC
settings[AVAudioFileTypeKey] = kAudioFileCAFType
settings[AVSampleRateKey] = buffer.format.sampleRate
settings[AVNumberOfChannelsKey] = 2
settings[AVLinearPCMIsFloatKey] = (buffer.format.commonFormat == .pcmFormatInt32)
do {
let tempFile = try AVAudioFile(forWriting: savePathUrl, settings: settings, commonFormat: buffer.format.commonFormat, interleaved: buffer.format.isInterleaved)
try tempFile.write(from: buffer)
} catch {
print(error)
}
case .failure(let failure):
print(failure.localizedDescription)
}
}
我遇到以下错误:CABufferList.h:179:BytesConsumed: ASSERTION FAILURE [(nBytes <= buf->mDataByteSize) != 0 is false]:
在我尝试做的那一行:
try tempFile.write(from: buffer)