編輯:關於 Android 程式設計
用 TTS 唸字很快樂,但每次都即時合成其實很浪費資源——TTS 引擎的運算與記憶體開銷都不小。如果你有一段固定的文本會被反覆播放,或者想把合成結果分享給沒有 TTS 引擎的朋友,那麼把語音存成音頻檔再播放,會是更聰明的做法。
public int synthesizeToFile(String text, HashMap<String, String> params, String filename)
三個參數的意思如下:
回傳 TextToSpeech.SUCCESS 代表合成成功。
這功能有幾個很實用的場合:把合成好的語音當附件傳給朋友,對方手機沒有 TTS 也能聽;長文本要播放很多次時,先存成檔案,之後純播放,省資源又快;多語言版本可以預先各存一份,依使用者地區切換播放。
下面就做一個實際的小 Demo:把想說的話合成語音存成 wav 檔,讓你可以把這份「錄音」送給對方。
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="https://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent" >
<EditText android:id="@+id/inputText"
android:hint="Input the text here!"
android:layout_width="fill_parent"
android:layout_height="wrap_content" />
<Button android:text="Speak" android:id="@+id/speakBtn"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center_horizontal"
android:enabled="false" />
<TextView android:id="@+id/filenameLabel"
android:text="Save as:"
android:layout_width="fill_parent"
android:layout_height="wrap_content" />
<EditText android:id="@+id/filenameText"
android:hint="Input the saving file name here!"
android:layout_width="fill_parent"
android:layout_height="wrap_content" />
<LinearLayout xmlns:android="https://schemas.android.com/apk/res/android"
android:orientation="horizontal"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:gravity="center_horizontal" >
<Button android:id="@+id/recordBtn" android:text="Record"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
<Button android:id="@+id/playBtn" android:text="Play"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:enabled="false" />
</LinearLayout>
</LinearLayout>
package com.example.androidttsdemo3;
import java.io.File;
import java.util.Locale;
import android.app.Activity;
import android.media.MediaPlayer;
import android.os.Bundle;
import android.speech.tts.TextToSpeech;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
public class MainActivity extends Activity implements TextToSpeech.OnInitListener {
private static final String TAG = "TTS Demo";
private static final String loveConfession = "Lan Hua, I love you. ";
private EditText inputText;
private Button speakBtn;
private EditText filenameText;
private Button recordBtn;
private Button playBtn;
private TextToSpeech mTts;
private String loveFileName;
private MediaPlayer player;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.fragment_main);
// 建立 TextToSpeech 實例;初始化完成後會回呼 OnInitListener
mTts = new TextToSpeech(this, this);
inputText = (EditText) findViewById(R.id.inputText);
speakBtn = (Button) findViewById(R.id.speakBtn);
filenameText = (EditText) findViewById(R.id.filenameText);
recordBtn = (Button) findViewById(R.id.recordBtn);
playBtn = (Button) findViewById(R.id.playBtn);
inputText.setText(loveConfession);
filenameText.setText("/sdcard/love.wav");
speakBtn.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
mTts.speak(inputText.getText().toString(), TextToSpeech.QUEUE_ADD, null);
}
});
recordBtn.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
loveFileName = filenameText.getText().toString();
File loveFile = new File(loveFileName);
if (loveFile.exists()) {
loveFile.delete();
}
if (TextToSpeech.SUCCESS ==
mTts.synthesizeToFile(inputText.getText().toString(), null, loveFileName)) {
Toast.makeText(getBaseContext(), "sound file created!", Toast.LENGTH_SHORT).show();
playBtn.setEnabled(true);
} else {
Toast.makeText(getBaseContext(), "failed to create sound file!", Toast.LENGTH_SHORT).show();
}
}
});
playBtn.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
try {
player = new MediaPlayer();
player.setDataSource(loveFileName);
player.prepare();
player.start();
} catch (Exception e) {
Toast.makeText(getBaseContext(), "failed to play sound file!", Toast.LENGTH_SHORT).show();
e.printStackTrace();
}
}
});
}
public void onInit(int status) {
if (status == TextToSpeech.SUCCESS) {
int result = mTts.setLanguage(Locale.US);
if (result == TextToSpeech.LANG_MISSING_DATA
|| result == TextToSpeech.LANG_NOT_SUPPORTED) {
Log.v(TAG, "Language is not available");
speakBtn.setEnabled(false);
} else {
speakBtn.setEnabled(true);
}
}
}
@Override
protected void onDestroy() {
// 一定要釋放 TTS 資源,否則引擎會被佔住
if (mTts != null) {
mTts.stop();
mTts.shutdown();
}
if (player != null) {
player.release();
player = null;
}
super.onDestroy();
}
}
new TextToSpeech() 之後引擎還沒準備好就呼叫 speak() 會失敗,所以範例刻意把 Speak 按鈕預設為 disabled,等 onInit 確認語言可用後才啟用。TextToSpeech.OnUtteranceProgressListener 監聽 onDone(),或改用 API 較新的 synthesizeToFile() 帶 File 參數的重載版本並註冊 listener。WRITE_EXTERNAL_STORAGE。較แนะำ的做法是寫進 App 專屬目錄 getExternalFilesDir(),免權限且卸载時自動清理。
美團 Android 資源混淆保護實踐全解析
前言 Android 應用的 APK 安全性一直為人詬病。市面上充斥著各種被破解或漢化的應用,破解者只需借助工具就能輕易對 APK 進行反編譯、破解、漢化,進而篡改原有代
這些編碼習慣正在洩漏你的記憶體:Android 常見內存洩漏陷阱
Android 的記憶體洩漏很少來自複雜的架構錯誤,絕大多數是幾個寫起來「很順手」的習慣累積出來的。以下幾個模式幾乎每個專案都會遇到,值得逐一檢視。 一、單例持有 Act
Android 事件分發機制(十三):dispatchTouchEvent 源碼逐段解析
事件分發的本質是一種委託:上層委託下層、父容器委託子元件去處理。要理解它,只需盯住一個類——MotionEvent,以及三個方法。 三個核心方法 dispatchTo
Android 屬性動畫、WebView 應用與圖片三級緩存實戰
屬性動畫 動畫:UI 漸變,也就是變量值的變化。 ObjectAnimator:ofInt(backgroundColor, start, end); ValueAnim