Android TextToSpeech(TTS)库允许您将文本转换为语音。要处理音频文件,您需要执行以下步骤:
- 添加依赖项:
在Android项目的
build.gradle
文件中,添加TextToSpeech库的依赖项:
dependencies { implementation 'com.android.support:appcompat-v7:28.0.0' implementation 'com.google.android.gms:play-services-tts:17.0.0' }
- 初始化TextToSpeech对象: 在您的Activity或Fragment中,初始化TextToSpeech对象并设置语言。
import android.speech.tts.TextToSpeech; import android.speech.tts.TextToSpeech.OnInitListener; public class MainActivity extends AppCompatActivity implements OnInitListener { private TextToSpeech tts; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); tts = new TextToSpeech(this, this); } @Override public void onInit(int status) { if (status == TextToSpeech.SUCCESS) { int language = TextToSpeech.LANG_ENGLISH; // 设置语言,例如英语 tts.setLanguage(language); } else { Log.e("TextToSpeech", "Initialization failed"); } } }
- 生成语音:
使用
TextToSpeech
类的synthesizeToFile()
方法将文本转换为音频文件。
import android.os.AsyncTask; import android.os.Environment; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; public class GenerateAudioTask extends AsyncTask{ private static final String DIRECTORY_NAME = "TTS_AUDIO"; private static final String FILE_EXTENSION = ".mp3"; @Override protected Void doInBackground(String... params) { String text = params[0]; String filePath = Environment.getExternalStorageDirectory().getAbsolutePath() + "/" + DIRECTORY_NAME; File directory = new File(filePath); if (!directory.exists()) { directory.mkdirs(); } String fileName = "output_" + System.currentTimeMillis() + FILE_EXTENSION; File audioFile = new File(filePath, fileName); try { tts.synthesizeToFile(text, TextToSpeech.QUEUE_FLUSH, audioFile.getAbsolutePath()); } catch (IOException e) { e.printStackTrace(); } return null; } }
- 播放音频文件:
使用
MediaPlayer
类播放生成的音频文件。
import android.media.MediaPlayer; public class PlayAudioActivity extends AppCompatActivity { private MediaPlayer mediaPlayer; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_play_audio); String filePath = Environment.getExternalStorageDirectory().getAbsolutePath() + "/TTS_AUDIO/output_1633027800000.mp3"; mediaPlayer = new MediaPlayer(); try { mediaPlayer.setDataSource(filePath); mediaPlayer.prepare(); mediaPlayer.start(); } catch (IOException e) { e.printStackTrace(); } } @Override protected void onDestroy() { super.onDestroy(); if (mediaPlayer != null) { mediaPlayer.release(); mediaPlayer = null; } } }
注意:在Android 6.0(API级别23)及更高版本中,需要在运行时请求存储权限。确保在AndroidManifest.xml
文件中添加以下权限:
并在运行时请求权限。