码迷,mamicode.com
首页 > 移动开发 > 详细

Android TTS文字转语音开发

时间:2015-02-05 13:42:01      阅读:281      评论:0      收藏:0      [点我收藏+]

标签:

<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);
		
	}

这样就可以了。

接下来讲一下如何实现语音识别



Android TTS文字转语音开发

标签:

原文地址:http://blog.csdn.net/shendan00/article/details/43525437

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!