Android TextToSpeech(TTS)庫允許您將文本轉換為語音。要處理音頻文件,您需要執行以下步驟:
build.gradle
文件中,添加TextToSpeech庫的依賴項:dependencies {
implementation 'com.android.support:appcompat-v7:28.0.0'
implementation 'com.google.android.gms:play-services-tts:17.0.0'
}
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<String, Void, Void> {
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
文件中添加以下權限:
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/>
并在運行時請求權限。