android tts语音转 mp3

以下是使用 Google Text-to-Speech 在 Android 应用程序中将文本转换为语音并将其保存为 MP3 文件的示例代码:

  1. 在 build.gradle 文件中添加以下依赖项:
dependencies {
    implementation 'com.google.android.gms:play-services-tasks:18.0.0'
}
  1. 在 AndroidManifest.xml 文件中添加以下权限:
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
  1. 在您的 Activity 中添加以下代码:
private TextToSpeech textToSpeech;
private String fileName = "audio.mp3";
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    textToSpeech = new TextToSpeech(this, new TextToSpeech.OnInitListener() {
        @Override
        public void onInit(int status) {
            if (status == TextToSpeech.SUCCESS) {
                textToSpeech.setLanguage(Locale.US);
                generateAudio("Hello World!");
            }
        }
    });
}
private void generateAudio(String text) {
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
        textToSpeech.synthesizeToFile(text, null, new File(getExternalFilesDir(null), fileName), null);
    } else {
        HashMap<String, String> map = new HashMap<>();
        map.put(TextToSpeech.Engine.KEY_PARAM_UTTERANCE_ID, "MessageId");
        textToSpeech.synthesizeToFile(text, map, new File(getExternalFilesDir(null), fileName).getAbsolutePath());
    }
}

这段代码将使用 Text-to-Speech 引擎生成 “Hello World!” 文本的语音,并将其保存为名为 “audio.mp3” 的文件。在 Android 5.0 及更高版本中,使用 synthesizeToFile() 方法将文本转换为语音,并指定要保存的文件名和位置。在 Android 4.4 及更低版本中,使用 synthesizeToFile() 方法,并传递一个包含 KEY_PARAM_UTTERANCE_ID 的 Map 对象,以确保语音转换完成后会调用 onUtteranceCompleted() 方法。

猜你喜欢

转载自blog.csdn.net/weixin_37077736/article/details/130401902