Amplify has re-imagined the way frontend developers build fullstack applications. Develop and deploy without the hassle.

Page updated Apr 29, 2024

Text-to-speech

Amplify iOS v1 is now in Maintenance Mode until May 31st, 2024. This means that we will continue to include updates to ensure compatibility with backend services and security. No new features will be introduced in v1.

Please use the latest version (v2) of Amplify Library for Swift to get started.

If you are currently using v1, follow these instructions to upgrade to v2.

Amplify libraries should be used for all new cloud connected applications. If you are currently using the AWS Mobile SDK for iOS, you can access the documentation here.

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:

? Please select from one of the categories below
Identify
❯ Convert
Interpret
Infer
Learn More
? What would you like to convert?
Translate text into a different language
❯ Generate speech audio from text
Transcribe text from audio
? Provide a friendly name for your resource
<Enter a friendly name here>
? What is the source language? (Use arrow keys)
<Select your default source language>
? Select a speaker (Use arrow keys)
<Select your default speaker voice>
? Who should have access?
Auth users only
❯ 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.

import Amplify
import AWSPredictionsPlugin
import AVFoundation
//...
var player: AVAudioPlayer?
//...
func textToSpeech(text: String) {
let options = PredictionsTextToSpeechRequest.Options(
voiceType: .englishFemaleIvy,
pluginOptions: nil
)
Amplify.Predictions.convert(textToSpeech: text, options: options) { event in
switch event {
case let .success(result):
print(result.audioData)
self.player = try? AVAudioPlayer(data: result.audioData)
if let player = self.player {
player.play()
}
case let .failure(error):
print(error)
}
}
}
import Amplify
import AWSPredictionsPlugin
import AVFoundation
//...
var player: AVAudioPlayer?
var textToSpeechSink: AnyCancellable?
//...
func textToSpeech(text: String) {
let options = PredictionsTextToSpeechRequest.Options(
voiceType: .englishFemaleIvy,
pluginOptions: nil
)
textToSpeechSink = Amplify.Predictions.convert(textToSpeech: text, options: options)
.resultPublisher
.sink {
if case let .failure(error) = $0 {
print(error)
}
}
receiveValue: { result in
print(result.audioData)
self.player = try? AVAudioPlayer(data: result.audioData)
if let player = self.player {
player.play()
}
}
}

As a result of running this code, you will hear audio of the text being emitted from your device.