我正在嘗試在 IOS 中使用文本到語音轉換(就像 TikTok 那樣)創建視頻。我認為這樣做的唯一方法是將視頻和音頻與 AVFoundations 合并,但似乎不可能將文本轉語音的音頻插入到 .caf 檔案中。
這是我嘗試過的:
public async Task amethod(string[] _text_and_position)
{
string[] text_and_position = (string[])_text_and_position;
double tts_starting_position = Convert.ToDouble(text_and_position[0]);
string text = text_and_position[1];
var synthesizer = new AVSpeechSynthesizer();
var su = new AVSpeechUtterance(text)
{
Rate = 0.5f,
Volume = 1.6f,
PitchMultiplier = 1.4f,
Voice = AVSpeechSynthesisVoice.FromLanguage("en-us")
};
synthesizer.SpeakUtterance(su);
Action<AVAudioBuffer> buffer = new Action<AVAudioBuffer>(asss);
try
{
synthesizer.WriteUtterance(su, buffer);
}
catch (Exception error) { }
}
public async void asss(AVAudioBuffer _buffer)
{
try
{
var pcmBuffer = (AVAudioPcmBuffer)_buffer;
if (pcmBuffer.FrameLength == 0)
{
// done
}
else
{
AVAudioFile output = null;
// append buffer to file
NSError error;
if (output == null)
{
string filePath = Path.Combine(Path.GetTempPath(), "TTS/" 1 ".caf");
NSUrl fileUrl = NSUrl.FromFilename(filePath);
output = new AVAudioFile(fileUrl, pcmBuffer.Format.Settings, AVAudioCommonFormat.PCMInt16 , false ,out error);
}
output.WriteFromBuffer(pcmBuffer, out error);
}
}
catch (Exception error)
{
new UIAlertView("Error", error.ToString(), null, "OK", null).Show();
}
}
這是objective-c中的相同代碼
let synthesizer = AVSpeechSynthesizer()
let utterance = AVSpeechUtterance(string: "test 123")
utterance.voice = AVSpeechSynthesisVoice(language: "en")
var output: AVAudioFile?
synthesizer.write(utterance) { (buffer: AVAudioBuffer) in
guard let pcmBuffer = buffer as? AVAudioPCMBuffer else {
fatalError("unknown buffer type: \(buffer)")
}
if pcmBuffer.frameLength == 0 {
// done
} else {
// append buffer to file
if output == nil {
output = AVAudioFile(
forWriting: URL(fileURLWithPath: "test.caf"),
settings: pcmBuffer.format.settings,
commonFormat: .pcmFormatInt16,
interleaved: false)
}
output?.write(from: pcmBuffer)
}
}
這段代碼的問題在于“synthesizer.WriteUtterance(su, buffer);” 總是崩潰,在閱讀其他帖子后,我相信這是一個導致回呼方法(緩沖區)永遠不會被呼叫的錯誤。
您是否知道此錯誤的任何解決方法或任何其他方式來實作我正在嘗試做的事情?
感謝您的時間,祝您有美好的一天。
編輯:我評論了 synthesizer.SpeakUtterance(su); 正如 ColeX 指出的那樣,現在執行回呼方法。不幸的是,我還不能將我的音頻存盤在一個檔案中,因為我在
output = new AVAudioFile(fileUrl, pcmBuffer.Format.Settings, AVAudioCommonFormat.PCMInt16 , false ,out error);
錯誤:
無法初始化 'AVFoundation.AVAudioFile' 型別的實體:本機 'initForWriting:settings:commonFormat:interleaved:error:' 方法回傳 nil。可以通過將 ObjCRuntime.Class.ThrowOnInitFailure 設定為 false 來忽略此條件。
uj5u.com熱心網友回復:
該錯誤僅顯示An AVSpeechUtterance shall not be enqueued twice.
所以不要讓它同時說話和寫作。
我使用了你的代碼并注釋掉synthesizer.SpeakUtterance(su);,錯誤消失了。
更新
根據我的測驗,它不允許創建額外的子檔案夾,因此洗掉該TTS/部分,只保留檔案名。
string filePath = Path.Combine(Path.GetTempPath(), 1 ".caf");
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/372463.html
標籤:C# ios 目标-c xamarin.forms 基金会
