Android TTS文字转语音开发
<span style="font-family: Arial, Helvetica, sans-serif; background-color: rgb(255, 255, 255);">之前在做TTS开发的时候能够正常的将文字转为语音,但是今天做了一个小程序,结果却发不了音,仔细测试了一下,发现了一个问题。</span>
首先先讲下TTS如何实现。
1、安装语音库,假如要中文发音,科大讯飞语音3.0就很好。
2、最简单的程序如下:
package com.example.tts; import java.util.Locale; import android.speech.tts.TextToSpeech; import android.support.v7.app.ActionBarActivity; import android.os.Bundle; import android.view.Menu; import android.view.MenuItem; import android.widget.Toast; public class MainActivity extends ActionBarActivity implements TextToSpeech.OnInitListener{ TextToSpeech textToSpeech = null; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); textToSpeech = new TextToSpeech(this, this); textToSpeech.speak("此处无声", TextToSpeech.QUEUE_ADD, null); } @Override public boolean onCreateOptionsMenu(Menu menu) { getMenuInflater().inflate(R.menu.main, menu); return true; } protected void onDestroy() { super.onDestroy(); if (textToSpeech!=null) { textToSpeech.shutdown(); } } @Override public boolean onOptionsItemSelected(MenuItem item) { int id = item.getItemId(); if (id == R.id.action_settings) { textToSpeech.speak("此处有声", TextToSpeech.QUEUE_FLUSH, null); return true; } return super.onOptionsItemSelected(item); } @Override public void onInit(int status) { // TODO Auto-generated method stub if (status == TextToSpeech.SUCCESS) { int result = textToSpeech.setLanguage(Locale.CHINESE); if (result == TextToSpeech.LANG_MISSING_DATA || result == TextToSpeech.LANG_NOT_SUPPORTED || result == TextToSpeech.ERROR) { Toast.makeText(this, "数据丢失或语言不支持", Toast.LENGTH_SHORT).show(); } if (result == TextToSpeech.LANG_AVAILABLE) { Toast.makeText(this, "支持该语言", Toast.LENGTH_SHORT).show(); } Toast.makeText(this, "初始化成功", Toast.LENGTH_SHORT).show(); } } }
无需任何权限,这里有个问题,就是在动态创建一个对象之后,在onCreate里面调用speak方法,并不能发出声音。
可以把文字保存为语音文件,也可以读取语音文件
public void saveToFile(TextToSpeech speech,String text,String file) { String destFileName = "/sdcard/tts/"+file+".wav"; speech.synthesizeToFile(text, null, destFileName); } public void readFromFile(TextToSpeech speech,String file) { String destFileName = "/sdcard/tts/"+file+".wav"; speech.addSpeech("2", destFileName); speech.speak("2", TextToSpeech.QUEUE_ADD, null); }
这样就可以了。
接下来讲一下如何实现语音识别
郑重声明:本站内容如果来自互联网及其他传播媒体,其版权均属原媒体及文章作者所有。转载目的在于传递更多信息及用于网络分享,并不代表本站赞同其观点和对其真实性负责,也不构成任何其他建议。