您的位置:首页 > 移动开发 > Android开发

Android进阶:Google自带语音播放功能实现

2011-12-14 23:35 267 查看
转自:http://blog.csdn.net/wanglong0537/article/details/6442999

在Android 中使用语音播放功能 只需要使用类 TextToSpeech ,该类实现了很多关于语音的功能,使用该类必须为其设置语言,现在支持五种语言,杯具的是不支持中文

实现很简单 不过首先要安装语言包 这个在设置--》语音输入和输出设置--》文字转语音设置

如下图







左边图中 安装语音数据 我这里已经安装成功了 所以是灰色的 如果没有安装这里就可以点 其他地方都是灰色的

安装文件4.28M 下载安装完成后就可以选择语言了 右图所示的五种语言 没有中文啊

下面来看实现 很简单






首先是layout文件:

view
plain


<?xml version="1.0" encoding="utf-8"?>

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"

android:orientation="vertical"

android:layout_width="fill_parent"

android:layout_height="fill_parent"

>

<EditText

android:id="@+id/EditText01"

android:layout_width="fill_parent"

android:text="I hope so, because it's time to wake up."

android:layout_height="wrap_content"

/>

<Button

android:id="@+id/Button01"

android:text="开始播放"

android:layout_width="fill_parent"

android:layout_height="wrap_content"

/>

</LinearLayout>

就是播放EditText中的内容

Acitivity中

view
plain


import java.util.Locale;

import android.app.Activity;

import android.os.Bundle;

import android.speech.tts.TextToSpeech;

import android.speech.tts.TextToSpeech.OnInitListener;

import android.util.Log;

import android.view.View;

import android.view.View.OnClickListener;

import android.widget.Button;

import android.widget.EditText;

public class VoisePlayDemo extends Activity {

private TextToSpeech mSpeech;

private Button btn;

private EditText mEditText;

@Override

public void onCreate(Bundle savedInstanceState) {

super.onCreate(savedInstanceState);

setContentView(R.layout.main);

btn = (Button) findViewById(R.id.Button01);

mEditText = (EditText) findViewById(R.id.EditText01);

btn.setEnabled(false);

//创建TextToSpeech对象

mSpeech = new TextToSpeech(this, new OnInitListener() {

@Override

public void onInit(int status) {

if (status == TextToSpeech.SUCCESS) {

int result = mSpeech.setLanguage(Locale.US);

if (result == TextToSpeech.LANG_MISSING_DATA

|| result == TextToSpeech.LANG_NOT_SUPPORTED) {

Log.e("bb", "not use");

} else {

btn.setEnabled(true);

}

}

}

});

btn.setOnClickListener(new OnClickListener() {

@Override

public void onClick(View v) {

mSpeech.speak(mEditText.getText().toString(),

TextToSpeech.QUEUE_FLUSH, null);

}

});

}

@Override

protected void onDestroy() {

if (mSpeech != null) {

mSpeech.stop();

mSpeech.shutdown();

}

super.onDestroy();

}

通过创建TextToSpeech类的实例 并在 onInit 初始化方法内判断语音加载是否成功 确实很简单了



就是不知道什么时候可以支持中文啊
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐