Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲

Android TTS 實戰:把語音合成結果存成音頻檔

編輯:關於 Android 程式設計

用 TTS 唸字很快樂,但每次都即時合成其實很浪費資源——TTS 引擎的運算與記憶體開銷都不小。如果你有一段固定的文本會被反覆播放,或者想把合成結果分享給沒有 TTS 引擎的朋友,那麼把語音存成音頻檔再播放,會是更聰明的做法。

一、關鍵 API

public int synthesizeToFile(String text, HashMap<String, String> params, String filename)

三個參數的意思如下:

  • text:要合成的文字。
  • params:鍵值對形式的參數,可指定語音片段 ID 等設定;一般傳 null 即可。
  • 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>

四、Java 實作

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 確認語言可用後才啟用。
  • 一定要 shutdown。TTS 引擎是系統層共享服務,忘記釋放會讓後續使用 TTS 的應用拿不到資源。
  • synthesizeToFile 也是非同步的。回傳 SUCCESS 只代表「任務已送出」,檔案可能還在寫。要確定完成,應該用 TextToSpeech.OnUtteranceProgressListener 監聽 onDone(),或改用 API 較新的 synthesizeToFile() 帶 File 參數的重載版本並註冊 listener。
  • 寫入 /sdcard 需要權限,且在 Android 6.0 之後要執行期申請 WRITE_EXTERNAL_STORAGE。較แนะำ的做法是寫進 App 專屬目錄 getExternalFilesDir(),免權限且卸载時自動清理。
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © Android教程網 All Rights Reserved