Richard
Richard

Reputation: 61

Google Text-To-Speech in swift

I am creating an app that has the text as input and must give out the speech as the output. I would like to send a function that I have created for fetching the text which will be the input and have the the text-to-speech return as the output. I have created a model for decoding the data generated from the Json data below for both input (JokesAPI), and output(ChatBotAPI). I have created a view controller that will return a speech for when the user taps a button. I am wondering, how can I implement this button for returning two separate functions when the button is tapped, both the text that is generated from the first API, and the text-to-speech that is generated from the google api ? Below is the functions that I have created for both getting data back from the APIs, and the button that I would like use for both functions

   // 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()
    }
}

//Model

 // 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
        
        
    }

Upvotes: 0

Views: 986

Answers (1)

Shabnam Siddiqui
Shabnam Siddiqui

Reputation: 614

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()
}

Upvotes: 1

Related Questions