使用TextToSpeech语音读取

今天无意见发现Android中有个控件可以实现语音读取,它就是TextToSpeech控件。目前只支持5种语言:English、 French 、 German 、 Italian 和 Spanish。(很遗憾没有 中文)。这个控件的好处是首先不要权限。

TextToSpeech必须再被实例化之后才能使用.实现TextToSpeech.OnInitListener方法来获取实例化结果的提醒。当你已经使用完TextToSpeech实例之后, 应该调用shutdown()方法来释放TextToSpeech所使用的本地资源。

内嵌的类:


     类型                                   名称                  功能
classTextToSpeech.Engine控制文字转化语音的常亮或者参数名
classTextToSpeech.EngineInfo已安装的语音引擎的信息
interfaceTextToSpeech.OnInitListener定义了语音引擎初始化结果的回调接口
interfaceTextToSpeech.OnUtteranceCompletedListenerAPI level 18被弃用 . 使用UtteranceProgressListener替代

常量:


        类型                                             名称                       功能
StringACTION_TTS_QUEUE_PROCESSING_COMPLETED广播事件,表示TextToSpeech转化器已经转化未所有处于语音队列的文本
intERROR表示一般的操作失败
intERROR_INVALID_REQUEST表示由于无效请求导致的失败
intERROR_NETWORK表示由于网络连接问题导致的失败
intERROR_NETWORK_TIMEOUT表示由于网络连接超时引起的失败
intERROR_NOT_INSTALLED_YET表示由于未完成的语音数据下载导致的错误
intERROR_OUTPUT表示输出产生的失败
intERROR_SERVICE表示由于TTS服务产生的失败
intERROR_SYNTHESIS表示由于引擎的输入转化的输入内容引起的失败
`intLANG_AVAILABLE表示本地语言可用,但不是方言或者引申语言(不知道对不对)
intLANG_COUNTRY_AVAILABLE表示本地语音或者方言可用,引申语音不可用
intLANG_COUNTRY_VAR_AVAILABLE表示本地语音可用
intLANG_MISSING_DATA语言包丢失
intLANG_NOT_SUPPORTED表示语音不支持
intQUEUE_ADD新的转化任务添加到队列后面
intQUEUE_FLUSH新的任务替代以前的任务,直接中断以前的任务
intSTOPPED表示由代理要求的停止
intSUCCESS操作成功


构造方法:


//使用默认的引擎
TextToSpeech(Context context, TextToSpeech.OnInitListener listener)
//使用指定的引擎
TextToSpeech(Context context, TextToSpeech.OnInitListener listener, String engine)

 
 



Demo

布局文件:

activity_speech.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    tools:context="com.example.testtexttospeech.TestTextToSpeechActivity">

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="vertical">

        <EditText
            android:id="@+id/edview"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:hint="请输入内容..."
            android:textSize="16dp"
            android:layout_marginTop="20dp"
            android:layout_marginBottom="20dp"/>

        <Button
            android:id="@+id/speechBtn"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:text="SpeechButton"/>

    </LinearLayout>

</RelativeLayout>
代码:
TestTextSpeechActivity.java
package com.example.testtexttospeech;

import android.app.Activity;
import android.speech.tts.TextToSpeech;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

import java.util.Locale;

public class TestTextToSpeechActivity extends Activity implements TextToSpeech.OnInitListener{

    private Button speechBtn;
    private EditText edview;
    private TextToSpeech textToSpeech;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_speech);

        textToSpeech = new TextToSpeech(this,this);

        edview = (EditText) findViewById(R.id.edview);
        speechBtn = (Button) findViewById(R.id.speechBtn);
        speechBtn.setEnabled(false);
        speechBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                String contextStr = edview.getText().toString().trim();
                if(TextUtils.isEmpty( contextStr )){
                    Toast.makeText(TestTextToSpeechActivity.this, "please input context",Toast.LENGTH_SHORT).show();
                    return;
                }
                initSpeech(contextStr);
            }
        });
    }

    @Override
    public void onInit(int status) {
        if( status == TextToSpeech.SUCCESS){
            int result = textToSpeech.setLanguage(Locale.US);
            if( result == TextToSpeech.LANG_MISSING_DATA || result == TextToSpeech.LANG_NOT_SUPPORTED){
               speechBtn.setEnabled(false);
                Log.e("TAG","Language is not available");
            }else{
                //TTS引擎已经成功初始化
                speechBtn.setEnabled(true);
            }
        }else{
            // 初始化失败
            Log.e( "TAG", "Could not initialize TextToSpeech.");
        }
    }

    private void initSpeech( String contextStr ){
        if( textToSpeech != null && !textToSpeech.isSpeaking()){
            textToSpeech.setPitch(0.5f); // 设置音调,值越大声音越尖(女生),值越小则变成男声,1.0是常规
            textToSpeech.speak( contextStr ,TextToSpeech.QUEUE_FLUSH, null);
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if( textToSpeech != null ){
            // 停止TextToSpeech
            textToSpeech.stop();
            //释放 TextToSpeech占用的资源
            textToSpeech.shutdown();
        }
    }
}


  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
### 回答1: Speech-to-Text自动语音识别可以使用Java代码实现。下面是一个简单的例子,使用Google Cloud Speech API: ``` import com.google.cloud.speech.v1.RecognitionAudio; import com.google.cloud.speech.v1.RecognitionConfig; import com.google.cloud.speech.v1.RecognitionConfig.AudioEncoding; import com.google.cloud.speech.v1.RecognizeResponse; import com.google.cloud.speech.v1.SpeechClient; import com.google.cloud.speech.v1.SpeechRecognitionAlternative; import com.google.protobuf.ByteString; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; import java.util.List; public class SpeechToText { public static void main(String... args) throws Exception { // Instantiates a client try (SpeechClient speechClient = SpeechClient.create()) { // The path to the audio file to transcribe String fileName = "path/to/audio.wav"; // Reads the audio file into memory Path path = Paths.get(fileName); byte[] data = Files.readAllBytes(path); ByteString audioBytes = ByteString.copyFrom(data); // Builds the sync recognize request RecognitionConfig config = RecognitionConfig.newBuilder() .setEncoding(AudioEncoding.LINEAR16) .setSampleRateHertz(16000) .setLanguageCode("zh-CN") .build(); RecognitionAudio audio = RecognitionAudio.newBuilder() .setContent(audioBytes) .build(); // Performs speech recognition on the audio file RecognizeResponse response = speechClient.recognize(config, audio); List<SpeechRecognitionAlternative> alternatives = response.getResultsList().get(0).getAlternativesList(); // Prints the transcription of each alternative for (SpeechRecognitionAlternative alternative : alternatives) { System.out.printf("Transcription: %s%n", alternative.getTranscript()); } } } } ``` 该代码使用Google Cloud Speech API对音频文件进行语音识别,并输出识别结果。请注意,需要设置Google Cloud API Key才能使用该API。 ### 回答2: 要实现Speech-to-Text自动语音识别方法,我们可以使用Java编写代码来实现。以下是一种可能的实现方法: 首先,我们需要导入Java中的相关库,如Java Speech API(JSAPI)和相关的语音识别库。可以通过以下代码导入库: ```java import javax.speech.*; import javax.speech.recognition.*; ``` 接下来,我们需要创建一个语音识别引擎,并加载相关的语法文件。可以通过以下代码实现: ```java Recognizer recognizer = Central.createRecognizer(new EngineModeDesc(Locale.ENGLISH)); recognizer.allocate(); File grammarFile = new File("grammar.gram"); // 语法文件路径 URL grammarURL = grammarFile.toURI().toURL(); Grammar grammar = recognizer.loadGrammarFromURL(grammarURL); ``` 然后,我们可以定义一个监听器,以便在识别到语音时进行相应的处理。可以通过以下代码定义监听器: ```java recognizer.addResultListener(new ResultAdapter() { public void resultAccepted(ResultEvent evt) { try { Result result = (Result)evt.getSource(); FinalRuleResult finalResult = (FinalRuleResult)result; String spokenText = finalResult.getBestFinalResultNoFiller(); // 处理识别到的文本 // ... System.out.println("识别结果:" + spokenText); } catch (Exception e) { e.printStackTrace(); } } }); ``` 最后,我们可以启动语音识别引擎,并开始录音以进行语音识别。可以通过以下代码实现: ```java recognizer.commitChanges(); recognizer.requestFocus(); recognizer.resume(); ``` 以上代码片段只是一个简单的示例,实际的实现可能会更加复杂,可以根据具体需求进行相应的扩展和改进。另外,还需要注意的是,该实现方法可能需要使用额外的语音识别库或服务来实现自动语音识别的功能。 ### 回答3: 实现Speech-to-Text自动语音识别方法的Java代码主要依赖于音频处理库和语音识别API。下面是一个简单的示例代码,以使用百度语音识别API为例。 首先,需要引入百度语音API的Java SDK及相关的依赖库。可以在百度开放平台下载并导入到项目中。 ```java import com.baidu.aip.speech.AipSpeech; import org.json.JSONObject; import java.io.File; import java.io.FileInputStream; import java.io.IOException; public class SpeechToText { public static final String APP_ID = "your_app_id"; public static final String API_KEY = "your_api_key"; public static final String SECRET_KEY = "your_secret_key"; public static void main(String[] args) throws IOException { // 初始化语音识别客户端 AipSpeech client = new AipSpeech(APP_ID, API_KEY, SECRET_KEY); // 设置音频输入流 File audioFile = new File("path_to_audio_file"); FileInputStream audioInputStream = new FileInputStream(audioFile); byte[] audioBytes = new byte[(int) audioFile.length()]; audioInputStream.read(audioBytes); // 调用语音识别API JSONObject result = client.asr(audioBytes, "pcm", 16000, null); if (result.getInt("err_no") == 0) { String text = result.getJSONArray("result").getString(0); System.out.println("识别结果:" + text); } else { System.out.println("识别失败:" + result.getString("err_msg")); } // 关闭音频输入流 audioInputStream.close(); } } ``` 在代码中,首先需要将自己在百度开放平台上创建的应用的APP_ID、API_KEY和SECRET_KEY替换成真实的值。然后,设置音频输入流,可以通过文件读取或者实时音频流的方式获取音频数据。最后,调用语音识别API,获取返回的识别结果。 请注意,以上是一个简单的示例代码,具体实现可能因使用语音识别API和音频处理库而有所差异。另外,还需要对代码进行异常处理以及参数的校验等操作,以保证代码的稳定性和功能完整性。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值