如何使TTS跳过字符串android中的特定单词

时间:2018-07-26 16:49:13

标签: android text-to-speech

这是我要问的第一个问题。我已经开发了一个Android应用程序,该应用程序使用广播接收器接收传入的短信,然后将消息与经过审查的单词的预定义数组列表进行比较,然后用*替换短信中的经过审查的单词 现在,我希望文本到语音来说出消息内容,但不要说经审查的单词是*。 我只需要一个准则或如何为此创建逻辑。 任何帮助将是非常有利的。我来这里的希望是希望能在这里找到帮助。 谢谢你

这是我的代码

import android.app.Activity;
import android.app.Dialog;
import android.content.ContentResolver;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.os.Bundle;
import android.provider.ContactsContract;
import android.speech.tts.TextToSpeech;
import android.speech.tts.UtteranceProgressListener;
import android.speech.tts.Voice;
import android.telephony.TelephonyManager;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;

import java.util.ArrayList;
import java.util.Locale;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class DialogActivity extends Activity implements View.OnClickListener
,TextToSpeech.OnInitListener

{

    TextView SMSsender,body;
    Button ok, dismissBtn;
    Dialog dialog;
    String strSender,strBody,contactName,contactNumber;

    TextToSpeech tts;

    ArrayList<String> offensiveWords;

    @Override
    protected void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);

        dialog = new Dialog(this);

        offensiveWords = new ArrayList<>();

        offensiveWords.add("Hack");
        offensiveWords.add("Offense");
        offensiveWords.add("Where");
        offensiveWords.add("Hell");

        dialog.setContentView(R.layout.dialog_layout);

        SMSsender = dialog.findViewById(R.id.sender);
        body = dialog.findViewById(R.id.textBody);

        ok = dialog.findViewById(R.id.readSMS);
        dismissBtn = dialog.findViewById(R.id.cancel);

        tts = new TextToSpeech(this,this,"com.google.android.tts");

        ok.setOnClickListener(this);
        dismissBtn.setOnClickListener(this);

        //Get Data from Intent
        Intent intent = getIntent();

        strSender = intent.getStringExtra("Sender");
        strBody = intent.getStringExtra("Body");

        //Check message for offensive words

        if(compareString(strBody,offensiveWords.get(0))
        ||compareString(strBody,offensiveWords.get(1))
        ||compareString(strBody,offensiveWords.get(2))
        ||compareString(strBody,offensiveWords.get(3))
        )
        {
            //--------------Put exact * characters as the words length-----------------
            //=========================================================================
            StringBuilder sbIndex0 = new StringBuilder();

            for(int i=0; i != offensiveWords.get(0).length(); i++)
                sbIndex0.append("*");

            strBody = strBody.replaceAll(offensiveWords.get(0),sbIndex0.toString());

            //=========================================================================

            StringBuilder sbIndex1 = new StringBuilder();

            for(int i=0; i != offensiveWords.get(1).length(); i++)
                sbIndex1.append("*");

            strBody = strBody.replaceAll(offensiveWords.get(1),sbIndex1.toString());

            //=========================================================================

            StringBuilder sbIndex2 = new StringBuilder();

            for(int i=0; i != offensiveWords.get(2).length(); i++)
                sbIndex2.append("*");

            strBody = strBody.replaceAll(offensiveWords.get(2),sbIndex2.toString());

            //=========================================================================

            StringBuilder sbIndex3 = new StringBuilder();

            for(int i=0; i != offensiveWords.get(3).length(); i++)
                sbIndex3.append("*");

            strBody = strBody.replaceAll(offensiveWords.get(3),sbIndex3.toString());

            //=========================================================================

        }

        //Show message
        body.setText(strBody);

        dialog.closeOptionsMenu();

        dialog.setTitle("Incoming SMS");

        //Check user contacts list
        getAllContacts();

        //If sender is in contact list then show sender name
        if(strSender.equalsIgnoreCase(contactNumber.replace(" ","")))
        {
            SMSsender.setText(contactName);
            strSender = contactName;
        }
        //else show sender number
        else
            SMSsender.setText(strSender);

        dialog.show();
    }

    @Override
    public void onClick(View view)
    {
        switch (view.getId())
        {

            case R.id.readSMS:
                //Start TTS Here

                TelephonyManager manager = (TelephonyManager) this.getSystemService(Context.TELEPHONY_SERVICE);

                //Country code of sender
                String countryCode = manager.getSimCountryIso();

                //strSender has the name of contact
                if(strSender.contains(contactName))
                    speakOut();

                //Speak message only
                else
                    speakUnknownNumber();


                break;

            case R.id.cancel:
                //Dismiss Dialog
                dialog.dismiss();
                //Shutdown Engine
                if(tts.isSpeaking())
                {
                    tts.stop();
                    tts.shutdown();
                }
                //Kill Activity
                finish();
                break;
        }
    }

    @Override
    public void onInit(int i)
    {
        if(i == TextToSpeech.SUCCESS)
        {
            int result = tts.setLanguage(Locale.US);

            if (result == TextToSpeech.LANG_MISSING_DATA
                    || result == TextToSpeech.LANG_NOT_SUPPORTED)
            {
                Log.e("TTS", "This Language is not supported");
            }
        }
        else
        {
            Toast.makeText(this,"Text To Speech Engine Failed",Toast.LENGTH_LONG).show();
        }
    }

    public void speakOut()
    {
        tts.setPitch(1.3f);
        tts.setSpeechRate(0.7f);
        tts.speak("Sms from "+strSender+
                "\n\n"+"Message\n\n"+strBody,TextToSpeech.QUEUE_ADD,null,null);

    }

    public void speakUnknownNumber()
    {
        tts.setPitch(1.3f);
        tts.setSpeechRate(0.7f);
        tts.speak("\n\n"+"Message\n\n"+strBody,TextToSpeech.QUEUE_ADD,null,null);
    }

    @Override
    protected void onPause()
    {
        super.onPause();
        if(tts != null)
        {
            tts.stop();
            tts.shutdown();
        }
    }

    //Read All contacts from phone
    public void getAllContacts()
    {
        ContentResolver cr = getContentResolver();
        Cursor cur = cr.query(ContactsContract.Contacts.CONTENT_URI,
                null, null, null, null);

        if ((cur != null ? cur.getCount() : 0) > 0)
        {
            while (cur != null && cur.moveToNext())
            {
                String id = cur.getString(
                        cur.getColumnIndex(ContactsContract.Contacts._ID));

                //Contact Name of sender if its present in address book
                contactName = cur.getString(cur.getColumnIndex(
                        ContactsContract.Contacts.DISPLAY_NAME));

                if (cur.getInt(cur.getColumnIndex(
                        ContactsContract.Contacts.HAS_PHONE_NUMBER)) > 0) {
                    Cursor pCur = cr.query(
                            ContactsContract.CommonDataKinds.Phone.CONTENT_URI,
                            null,
                            ContactsContract.CommonDataKinds.Phone.CONTACT_ID + " = ?",
                            new String[]{id}, null);
                    while (pCur.moveToNext())
                    {
                        contactNumber = pCur.getString(pCur.getColumnIndex(
                                ContactsContract.CommonDataKinds.Phone.NUMBER));
                    }
                    pCur.close();
                }
            }
        }
        if(cur!=null)
        {
            cur.close();
        }

    } //End of getAllContacts


    //Method for matching censored words
    public boolean compareString(String source,String item)
    {
        String pattern = "(?<!\\S)" + item + "(?!\\S)";
        Pattern p = Pattern.compile(pattern);
        Matcher m = p.matcher(source);
        return m.find();
    }
}

1 个答案:

答案 0 :(得分:0)

因此,经过大量的努力,我找到了一种不错的方法。 创建另一个字符串,并将结果存储在不带有冒犯性词的字符串中,并使用***显示该字符串,但读取干净的字符串..

示例代码为

//Show message
        body.setText(strBody);

        //Extract string without offensive words

        cleanString = strBody;

        cleanString = cleanString.replace("*","");

        //=========================

然后说出来

public void speakUnknownNumber()
    {
        tts.setPitch(1.3f);
        tts.setSpeechRate(0.7f);
        tts.speak("\n\n"+"Message\n\n"+cleanString,TextToSpeech.QUEUE_ADD,null,null);
    }

**输出 strBody =什么**** ==>这里的****是地狱 cleanString =什么 **

所以tts只讲干净的话。

希望这可以帮助其他遇到相同问题的人。 干杯