textToSpeech method
- String text
Converts text to speech using an API.
Sends a POST request to the text-to-speech API with the provided text
,
and saves the resulting audio file in the application's documents directory.
Returns a File containing the audio data if successful, or null
if an error occurs.
Throws a TimeoutException if the request takes longer than 10 seconds indicating an error.
Implementation
Future<File?> textToSpeech(String text) async {
// final url = Uri.parse('http://10.0.2.2:8440/text-to-speech');
final url= Uri.parse('$baseUrl/text-to-speech');
final headers = {'Content-Type': 'application/json'};
final body = jsonEncode(
{'model': 'deepgram_tts', 'content': text, "voice": "aura-helios-en"});
try {
final response = await http
.post(url, headers: headers, body: body)
.timeout(Duration(seconds: 10));
;
if (response.statusCode == 200) {
final directory = await getApplicationDocumentsDirectory();
final filePath = '${directory.path}/audio.wav';
final file = File(filePath);
await file.writeAsBytes(response.bodyBytes);
return file;
} else {
print('Failed to convert text to speech');
return null;
}
} on TimeoutException catch (_) {
print('Request to text-to-speech API timed out');
return null;
} catch (e) {
print('Error: $e');
return null;
}
}