我正在创建一个应用程序,它的文本作为输入,必须给出演讲作为输出。我想发送一个函数,我已经创建了获取文本,这将是输入,并有文本到语音返回作为输出。我创建了一个模型,用于解码从下面的Json数据中为输入(JokesAPI)和输出(ChatBotAPI)生成的数据。我已经创建了一个视图控制器,当用户点击按钮时,它将返回一个演讲。我想知道,当按钮被点击时,我如何实现这个按钮返回两个不同的函数,从第一个API生成的文本,以及从google生成的文本到语音?下面是我为从APIs中获取数据而创建的函数,以及我希望用于这两个函数的按钮
// the function for the Text that the google text-speech will use as an input
func fetchJokes()
// The function that grabs the data from google
import Foundation
class ChatBotAPI {
var session: URLSession?
var API_KEY = doSomethingDope
func fetchTextToSpeech(key: String, completion: @escaping ([Voice]) -> Void, error errorHandler: @escaping (String?) -> Void){
guard let url = URL(string: "https://cloud.google.com/text-to-speech/docs/reference/rest/?apix=true#service:-texttospeech.googleapis.com")
else {
errorHandler("Invalid URL endpoint")
return
}
guard let key = API_KEY else {
print("Can not generate these parameters for the API Key")
return
}
let request = URLRequest(url: url)
let task = URLSession.shared.dataTask(with: request) { data, response, error in
if let error = error {
errorHandler(error.localizedDescription)
return
}
guard let response = response
else {
errorHandler("Could not generate a response")
return
}
struct ChatBotResponse: Decodable {
let data: [Voice]
}
guard let data = data else {
errorHandler("No data")
return
}
do {
let chatBotResponse = try JSONDecoder().decode(ChatBotResponse.self, from: data)
completion(chatBotResponse.data)
} catch {
print("Error decoding chat bot response:", error)
errorHandler("Something went wrong")
}
}
task.resume()
}
}//模型
// MARK: - Voice
struct Voice: Decodable {
let audioConfig: AudioConfig
let input: Input
let voice: VoiceClass
}
// MARK: - AudioConfig
struct AudioConfig: Decodable {
let audioEncoding: String
let effectsProfileID: [String]
let pitch, speakingRate: Double
enum CodingKeys: String, CodingKey {
case audioEncoding
case effectsProfileID = "effectsProfileId"
case pitch, speakingRate
}
}
// MARK: - Input
struct Input: Decodable {
let text: String
}
// MARK: - VoiceClass
struct VoiceClass: Decodable {
let languageCode, name: String
}
// ViewController with button
@IBAction func didPressBtn() {
// MARK: Actions for both fetching a joke from the API, & Text-Speech using AI Voice
}发布于 2021-12-30 08:10:29
func fetchJokes()
{
//whenever you get the response of jokes, call the function fetchTextToSpeech by passing jokes as string
let joke = "This is a joke. This is only a joke."
fetchTextToSpeech(strJokes: joke)
}
func fetchTextToSpeech(strJokes : String)
{
var speechSynthesizer = AVSpeechSynthesizer()
var speechUtterance: AVSpeechUtterance = AVSpeechUtterance(string: strJokes)
speechUtterance.rate = AVSpeechUtteranceMaximumSpeechRate / 3.0
speechUtterance.voice = AVSpeechSynthesisVoice(language: "en-US")
speechSynthesizer.speak(speechUtterance)
}
@IBAction func didPressBtn() {
fetchJokes()
}https://stackoverflow.com/questions/70528015
复制相似问题