android:如何在非活动课堂上使用文本进行语音交流 [英] android:how to use text to speech on non activity class

查看:64
本文介绍了android:如何在非活动课堂上使用文本进行语音交流的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想在应用程序中使用文本进行语音转换,我发现了许多使用文本进行语音转换的示例,例如

i want to use text to speech in my application, i find many example for using text to speech like this Android Text-To-Speech Application . i want to use text to speech from non activity class , for example i have class that genrate layout and return this layout to my main activity , ihave button on this layout and i want to when clicked on this button call text to speech. how can i use text to speech on non activity class ?

推荐答案

按如下所示创建您的Speech类:

Create your Speech class as below:

package zillion;

import android.content.Context;
import android.speech.tts.TextToSpeech;
import android.widget.Toast;

import java.util.Locale;


public class Speech {
    private static TextToSpeech tts;
    private static CharSequence SC_str;
    private static String S_str;

    public static void Talk(Context context, String str) {
        Toast.makeText(context, str, Toast.LENGTH_SHORT).show();
        S_str = str;
        tts = new TextToSpeech(Zillion.getContext(), new TextToSpeech.OnInitListener() {

            @Override
            public void onInit(int status) {
                if(status != TextToSpeech.ERROR) {
                    tts.setLanguage(Locale.UK);
                    tts.setPitch(1.3f);
                    tts.setSpeechRate(1f);
                 //   tts.speak(SC_str, TextToSpeech.QUEUE_FLUSH, null,null);
                    tts.speak(S_str, TextToSpeech.QUEUE_FLUSH, null);
                }
            }
        });
    }
}

如您所见,Zillion.getContext()已被替换为getApplicationContext(),要获取上下文,您需要创建一个类扩展应用程序,如下所示:

As you noticed Zillion.getContext() had been used as replacement of getApplicationContext(), to get the context, you need to create a class extends application, like below:

package zillion;

import android.app.Application;
import android.content.Context;

public class Zillion extends Application {

    private static Context mContext;

    @Override
    public void onCreate() {
        super.onCreate();
        mContext = getApplicationContext();
    }

    public static Context getContext() {
        return mContext;
    }
}

,然后在与此类相关的清单中将应用定义为:

and define the app in the manifest related to this class as:

<application
        android:name=".Zillion"
</application>

这篇关于android:如何在非活动课堂上使用文本进行语音交流的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆