非活动课中如何实现文本转语音

发布于 2024-11-30 05:08:01 字数 3981 浏览 0 评论 0 原文

我想在非活动类中实现文本到语音,我希望当用户单击自定义 ListView 时听到所写的单词。

接下来的代码是:

public class BankAdapter extends BaseAdapter {


List<BankItem> items;
LayoutInflater inflater;

//实现 TextToSpeech 的类

**TextToSpeach ttl1;**

OnClickListener l;

static class BankItemHolder {

    TextView wordView;
    TextView descriptionView;

}

Activity myMainActivity;

    public BankAdapter(Activity mainActivity) {
    // TODO Auto-generated constructor stub
       super();
       this.myMainActivity=mainActivity;
}

public BankAdapter(Context ctx, List<BankItem> items) {
    this.items = items;
    inflater =(LayoutInflater)ctx.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}

。 。 。 。 。

public View getView(final int position, View convertView, ViewGroup parent) {
        final BankItemHolder bih;
        if (convertView == null) {
            RelativeLayout rl = (RelativeLayout) inflater.inflate(R.layout.v_bank_item, null);
            convertView = rl;
            bih = new BankItemHolder();
            bih.wordView = (TextView) rl.findViewById(R.id.txtWord);
            bih.descriptionView = (TextView) rl.findViewById(R.id.txtDescription);
            convertView.setTag(bih);
        } else {
            bih = (BankItemHolder) convertView.getTag();
        }       



        bih.wordView.setText(items.get(position).getWord());
        bih.descriptionView.setText(items.get(position).getDescriprion());

        l=new OnClickListener() {

            public void onClick(View v) {
                // TODO Auto-generated method stub
                String w1 = items.get(position).getWord();
                int i1 = w1.indexOf(" ");
                String w2=w1.substring(0, i1);


                **ttl1.speakWords(w2);**
            }
        };;;

        convertView.setOnClickListener(l);  
        return convertView;

。 。 。 。

}

}

实现 TextToSpeech 的类

public class TextToSpeach extends Activity implements OnInitListener {

private int MY_DATA_CHECK_CODE = 0;

private TextToSpeech tts;

/**
 * Called when the activity is first created.
 */
@Override
public void onCreate(Bundle savedInstanceState)
{
    super.onCreate(savedInstanceState);
  //  setContentView(R.layout.main);

    // Fire off an intent to check if a TTS engine is installed
    Intent checkIntent = new Intent();
    checkIntent.setAction(TextToSpeech.Engine.ACTION_CHECK_TTS_DATA);
    startActivityForResult(checkIntent, MY_DATA_CHECK_CODE);

}



public void speakWords(String word) {

    tts.speak(word, TextToSpeech.QUEUE_ADD, null);

}

protected void onActivityResult(int requestCode, int resultCode, Intent data) {

    if (requestCode == MY_DATA_CHECK_CODE) {
        if (resultCode == TextToSpeech.Engine.CHECK_VOICE_DATA_PASS) {
            // success, create the TTS instance
            tts = new TextToSpeech(this, this);
        } 
        else {
            // missing data, install it
            Intent installIntent = new Intent();
            installIntent.setAction(TextToSpeech.Engine.ACTION_INSTALL_TTS_DATA);
            startActivity(installIntent);
        }
    }

}

public void onInit(int status) {        
    if (status == TextToSpeech.SUCCESS) {
        Toast.makeText(TextToSpeach.this, "Text-To-Speech engine is initialized", Toast.LENGTH_LONG).show();
    }
    else if (status == TextToSpeech.ERROR) {
        Toast.makeText(TextToSpeach.this, "Error occurred while initializing Text-To-Speech engine", 
                Toast.LENGTH_LONG).show();
    }
}

 /**
 * Be kind, once you've finished with the TTS engine, shut it down so other
 * applications can use it without us interfering with it :)
 */
@Override
public void onDestroy()
{
    // Don't forget to shutdown!
    if (tts != null)
    {
        tts.stop();
        tts.shutdown();
    }
    super.onDestroy();
}

现在是

I want to implement text to speech in non-activity class, I want when user click on custom ListView to listen the word who is written.

The code is next:

public class BankAdapter extends BaseAdapter {


List<BankItem> items;
LayoutInflater inflater;

//class who implements TextToSpeech

**TextToSpeach ttl1;**

OnClickListener l;

static class BankItemHolder {

    TextView wordView;
    TextView descriptionView;

}

Activity myMainActivity;

    public BankAdapter(Activity mainActivity) {
    // TODO Auto-generated constructor stub
       super();
       this.myMainActivity=mainActivity;
}

public BankAdapter(Context ctx, List<BankItem> items) {
    this.items = items;
    inflater =(LayoutInflater)ctx.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}

.
.
.
.
.

public View getView(final int position, View convertView, ViewGroup parent) {
        final BankItemHolder bih;
        if (convertView == null) {
            RelativeLayout rl = (RelativeLayout) inflater.inflate(R.layout.v_bank_item, null);
            convertView = rl;
            bih = new BankItemHolder();
            bih.wordView = (TextView) rl.findViewById(R.id.txtWord);
            bih.descriptionView = (TextView) rl.findViewById(R.id.txtDescription);
            convertView.setTag(bih);
        } else {
            bih = (BankItemHolder) convertView.getTag();
        }       



        bih.wordView.setText(items.get(position).getWord());
        bih.descriptionView.setText(items.get(position).getDescriprion());

        l=new OnClickListener() {

            public void onClick(View v) {
                // TODO Auto-generated method stub
                String w1 = items.get(position).getWord();
                int i1 = w1.indexOf(" ");
                String w2=w1.substring(0, i1);


                **ttl1.speakWords(w2);**
            }
        };;;

        convertView.setOnClickListener(l);  
        return convertView;

.
.
.
.

}

}

Now the class who implements TextToSpeech

public class TextToSpeach extends Activity implements OnInitListener {

private int MY_DATA_CHECK_CODE = 0;

private TextToSpeech tts;

/**
 * Called when the activity is first created.
 */
@Override
public void onCreate(Bundle savedInstanceState)
{
    super.onCreate(savedInstanceState);
  //  setContentView(R.layout.main);

    // Fire off an intent to check if a TTS engine is installed
    Intent checkIntent = new Intent();
    checkIntent.setAction(TextToSpeech.Engine.ACTION_CHECK_TTS_DATA);
    startActivityForResult(checkIntent, MY_DATA_CHECK_CODE);

}



public void speakWords(String word) {

    tts.speak(word, TextToSpeech.QUEUE_ADD, null);

}

protected void onActivityResult(int requestCode, int resultCode, Intent data) {

    if (requestCode == MY_DATA_CHECK_CODE) {
        if (resultCode == TextToSpeech.Engine.CHECK_VOICE_DATA_PASS) {
            // success, create the TTS instance
            tts = new TextToSpeech(this, this);
        } 
        else {
            // missing data, install it
            Intent installIntent = new Intent();
            installIntent.setAction(TextToSpeech.Engine.ACTION_INSTALL_TTS_DATA);
            startActivity(installIntent);
        }
    }

}

public void onInit(int status) {        
    if (status == TextToSpeech.SUCCESS) {
        Toast.makeText(TextToSpeach.this, "Text-To-Speech engine is initialized", Toast.LENGTH_LONG).show();
    }
    else if (status == TextToSpeech.ERROR) {
        Toast.makeText(TextToSpeach.this, "Error occurred while initializing Text-To-Speech engine", 
                Toast.LENGTH_LONG).show();
    }
}

 /**
 * Be kind, once you've finished with the TTS engine, shut it down so other
 * applications can use it without us interfering with it :)
 */
@Override
public void onDestroy()
{
    // Don't forget to shutdown!
    if (tts != null)
    {
        tts.stop();
        tts.shutdown();
    }
    super.onDestroy();
}

}

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

划一舟意中人 2024-12-07 05:08:01

当你想在 android 上下文之外使用 Android 框架时,这个问题是有症状的。

从我的一点经验和讲座来看,
这是我自己在这个问题上的最佳实践。

首先:

自定义服务、活动、广播接收器、ContentProvider 是 android 上下文和/或随 android 上下文一起提供。
这个上下文对于访问 android 服务非常重要。

TTS 也不例外:它需要使用上下文和侦听器进行实例化,以便在它准备好时进行通知(在构造时未准备好),

因此您可以在非 GUI 组件(例如服务)中执行 TextToSpeech 操作。

第二:

避免在同一代码中混合使用应用程序逻辑和 GUI 来设计代码

第三:

如果逻辑需要在 Android 框架上运行,那么这是一个仅在运行时需要时提供上下文的好方法(例如作为参数)
例如:上下文可以是服务或活动实例。

第四:

尽可能避免保留对上下文的引用。
因为android框架,对于内存分配策略,可能会自行决定破坏/重建上下文。

希望有帮助

This question is symptomatic when you want to use Android framework outside of a android context..

From my little experience and lecture,
Here my own best practice in this question context.

FIRST:

Custom Service, Activity, Broadcastreceiver, ContentProvider are android context and/or are provided with android context.
This context is very important to get access to android services.

TTS is not in exception : it needs to be intantiated with a context and a listener to notify when it is ready (not ready at contruction time)

So you may do TextToSpeech actions in non-GUI component like a service for instance.

SECOND:

Avoid to design your code with a mix of App Logic and GUI in same code

THIRD:

if logic need to act on android framework it's a good way to provide context only when needed at runtime (as a parameter for instance)
as example : context can be a service or activity instance.

FOURTH:

Avoid as much as possible to keep reference to a context.
because android framework,for memory allocation strategy, may destroy /reconstruct context at it's own discretion.

hope that help

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文