Text-to-speech
Set up the backend
If you haven't already done so, run amplify init
inside your project and then amplify add auth
(we recommend selecting the default configuration).
Run amplify add predictions
, then use the following answers:
1? Please select from one of the categories below2 Identify3❯ Convert4 Interpret5 Infer6 Learn More7 8? What would you like to convert?9 Translate text into a different language10❯ Generate speech audio from text11 Transcribe text from audio12
13? Provide a friendly name for your resource14 <Enter a friendly name here>15 16? What is the source language? (Use arrow keys)17 <Select your default source language>18
19? Select a speaker (Use arrow keys)20 <Select your default speaker voice>21 22? Who should have access?23 Auth users only24❯ Auth and Guest users
Run amplify push
to create the resources in the cloud
Working with the API
Here is an example of converting text to speech. In order to override any choices you made while adding this resource using the Amplify CLI, you can pass in a voice in the options object as shown below.
1import Amplify2import AWSPredictionsPlugin3import AVFoundation4
5//...6
7var player: AVAudioPlayer?8
9//...10
11func textToSpeech(text: String) {12 let options = PredictionsTextToSpeechRequest.Options(13 voiceType: .englishFemaleIvy,14 pluginOptions: nil15 )16
17 Amplify.Predictions.convert(textToSpeech: text, options: options) { event in18 switch event {19 case let .success(result):20 print(result.audioData)21 self.player = try? AVAudioPlayer(data: result.audioData)22 if let player = self.player {23 player.play()24 }25 case let .failure(error):26 print(error)27 }28 }29}
1import Amplify2import AWSPredictionsPlugin3import AVFoundation4
5//...6
7var player: AVAudioPlayer?8var textToSpeechSink: AnyCancellable?9
10//...11
12func textToSpeech(text: String) {13 let options = PredictionsTextToSpeechRequest.Options(14 voiceType: .englishFemaleIvy,15 pluginOptions: nil16 )17
18 textToSpeechSink = Amplify.Predictions.convert(textToSpeech: text, options: options)19 .resultPublisher20 .sink {21 if case let .failure(error) = $0 {22 print(error)23 }24 }25 receiveValue: { result in26 print(result.audioData)27 self.player = try? AVAudioPlayer(data: result.audioData)28 if let player = self.player {29 player.play()30 }31 }32}
As a result of running this code, you will hear audio of the text being emitted from your device.