Untitled
unknown
plain_text
a year ago
3.3 kB
9
Indexable
implementation 'com.google.cloud:google-cloud-texttospeech:1.0.0' implementation 'com.google.api-client:google-api-client-android:1.30.10' implementation 'com.google.http-client:google-http-client-gson:1.30.1' import com.google.api.gax.core.FixedCredentialsProvider; import com.google.auth.oauth2.GoogleCredentials; import com.google.cloud.texttospeech.v1.AudioConfig; import com.google.cloud.texttospeech.v1.AudioEncoding; import com.google.cloud.texttospeech.v1.Input; import com.google.cloud.texttospeech.v1.SsmlVoiceGender; import com.google.cloud.texttospeech.v1.SynthesisInput; import com.google.cloud.texttospeech.v1.SynthesizeSpeechResponse; import com.google.cloud.texttospeech.v1.TextToSpeechClient; import com.google.cloud.texttospeech.v1.TextToSpeechSettings; import com.google.cloud.texttospeech.v1.VoiceSelectionParams; import java.io.FileInputStream; import java.io.OutputStream; import android.media.MediaPlayer; import android.os.Bundle; import androidx.appcompat.app.AppCompatActivity; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; public class MainActivity extends AppCompatActivity { private TextToSpeechClient textToSpeechClient; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); try { // Initialize the Text-to-Speech client FileInputStream credentialsStream = new FileInputStream("path/to/your/api-key-file.json"); GoogleCredentials credentials = GoogleCredentials.fromStream(credentialsStream); TextToSpeechSettings settings = TextToSpeechSettings.newBuilder() .setCredentialsProvider(FixedCredentialsProvider.create(credentials)) .build(); textToSpeechClient = TextToSpeechClient.create(settings); // Call the Text-to-Speech API String text = "Hello, world!"; SynthesisInput input = SynthesisInput.newBuilder().setText(text).build(); VoiceSelectionParams voice = VoiceSelectionParams.newBuilder() .setLanguageCode("en-US") .setSsmlVoiceGender(SsmlVoiceGender.NEUTRAL) .build(); AudioConfig audioConfig = AudioConfig.newBuilder() .setAudioEncoding(AudioEncoding.MP3) .build(); SynthesizeSpeechResponse response = textToSpeechClient.synthesizeSpeech(input, voice, audioConfig); // Get the audio content and play it byte[] audioContents = response.getAudioContent().toByteArray(); File tempFile = File.createTempFile("tts", "mp3", getCacheDir()); try (OutputStream os = new FileOutputStream(tempFile)) { os.write(audioContents); } MediaPlayer mediaPlayer = new MediaPlayer(); mediaPlayer.setDataSource(tempFile.getAbsolutePath()); mediaPlayer.prepare(); mediaPlayer.start(); } catch (Exception e) { e.printStackTrace(); } } @Override protected void onDestroy() { super.onDestroy(); if (textToSpeechClient != null) { textToSpeechClient.close(); } } }
Editor is loading...
Leave a Comment