java - Android TTS如何在textview中显示说话的单词

标签 java android button text-to-speech google-text-to-speech

如何在说话时将 tts 输出显示为 TextView 。 实际上我想在 TextView 中显示 tts 输出单词。我有 1 个编辑文本,在其中输入一些数据,然后当单击播放按钮时它会执行语音,但我也想在 TextView 中显示说话的单词,我该如何做到这一点,任何人都可以帮助我。我还考虑将文本转换为数组形式然后通过,但是,我认为它没有其他解决方案有用? 我目前正在做的代码。

例如:如果 TTS 正在说出此字符串:How are you!当它达到“如何”时,如何在 TextView 中仅显示“如何”单个单词。

Initializations();
        textToSpeech = new TextToSpeech(MainActivity.this, new TextToSpeech.OnInitListener() {
            @Override
            public void onInit(int status) {
                if (status == TextToSpeech.SUCCESS) {
                    int result = textToSpeech.setLanguage(Locale.ENGLISH);
                    if (result == TextToSpeech.LANG_MISSING_DATA) {
                        Toast.makeText(MainActivity.this, "Sorry ! Language data missing", Toast.LENGTH_SHORT).show();
                    } else if (result == TextToSpeech.LANG_NOT_SUPPORTED) {
                        Toast.makeText(MainActivity.this, "Sorry ! Language not supported", Toast.LENGTH_SHORT).show();
                    } else {
                        speek.setEnabled(true);
                    }
                } else if (status == TextToSpeech.ERROR) {
                    Toast.makeText(MainActivity.this, "Sorry ! Text to speech can't be initialized", Toast.LENGTH_SHORT).show();
                    speek.setEnabled(false);
                }
            }
        });
        speek.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                SpeekOut();
            }
        });
private void SpeekOut() {
        String text = etTextToSpeech.getText().toString();
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            textToSpeech.speak(text, TextToSpeech.QUEUE_FLUSH, null, null);
        } else {
            textToSpeech.speak(text, TextToSpeech.QUEUE_FLUSH, null);
        }
    }

最佳答案

尝试阅读

在任何按钮点击中添加此内容。

Intent intent = new Intent(RecognizerIntent.ACTION_RECOGNIZE_SPEECH);
                intent.putExtra(RecognizerIntent.EXTRA_LANGUAGE_MODEL, "en-US");
                Intent i = new Intent(MainService.ACTION);
                if (isServiceRunning()) {
                    stopService(i);
                    ((NotificationManager) getSystemService(NOTIFICATION_SERVICE))
                            .cancelAll();

                } else {
                    startService(i);

                    runAsForeground();

                }

                try { startActivityForResult(intent, RESULT_SPEECH);
                    txtText.setText("");
                } catch (ActivityNotFoundException a) {
                    Toast t = Toast.makeText(getApplicationContext(), "Opps! Your device doesn't support Speech to Text", Toast.LENGTH_SHORT); t.show();
                }

//这里是runAsForeground函数

private void runAsForeground(){
        Intent notificationIntent = new Intent(this, MainActivity.class);
        PendingIntent pendingIntent=PendingIntent.getActivity(this, 0,
                notificationIntent, Intent.FLAG_ACTIVITY_NEW_TASK);

        Notification notification=new NotificationCompat.Builder(this)
                                    .setSmallIcon(R.drawable.ic_launcher)
                                    .setContentTitle(getString(R.string.app_name))
                                    .setContentText("Night Mode")
                                    .setContentIntent(pendingIntent).build();
        NotificationManager notificationManager = 
                (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
      notification.flags = notification.flags
              | Notification.FLAG_ONGOING_EVENT;
      notification.flags |= Notification.FLAG_AUTO_CANCEL;

      notificationManager.notify(0, notification);     
    }

在 TextView 中显示

@Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        switch (requestCode) {
            case RESULT_SPEECH: {
                if (resultCode == RESULT_OK && null != data) {
                    ArrayList<String> text = data
                            .getStringArrayListExtra(RecognizerIntent.EXTRA_RESULTS);

                    txtText.setText(text.get(0));
                }
                break;

            }
        }
    }

//主服务

import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;

import android.app.Service;
import android.content.ContentResolver;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.media.MediaRecorder;
import android.net.Uri;
import android.os.Environment;
import android.os.IBinder;
import android.os.PowerManager;
import android.provider.ContactsContract.PhoneLookup;
import android.util.Log;

public class MainService extends Service {
    public static final String ACTION = "com.thul.CallRecorder.CALL_RECORD";
    public static final String STATE = "STATE";
    public static final String START = "START";
    public static final String STORAGE = "STORAGE";
    public static final String INCOMING = "INCOMING";
    public static final String OUTGOING = "OUTGOING";
    public static final String BEGIN = "BEGIN";
    public static final String END = "END";

    protected static final String TAG = MainService.class.getName();
    protected static final boolean DEBUG = false;

    private static final String AMR_DIR = "/callrec/";
    private static final String IDLE = "";
    private static final String INCOMING_CALL_SUFFIX = "_i";
    private static final String OUTGOING_CALL_SUFFIX = "_o";

    private Context cntx;
    private volatile String fileNamePrefix = IDLE;
    private volatile MediaRecorder recorder;
    private volatile PowerManager.WakeLock wakeLock;
    private volatile boolean isMounted = false;
    private volatile boolean isInRecording = false;

    @Override
    public IBinder onBind(Intent i) {
        return null;
    }

    @Override
    public void onCreate() {
        // TODO Auto-generated method stub
        super.onCreate();
        this.cntx = getApplicationContext();
        this.prepareAmrDir();
        log("service create");
    }

    @Override
    public void onDestroy() {
        log("service destory");
        this.stopRecording();
        this.cntx = null;
        super.onDestroy();
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        if (null == intent || !ACTION.equals(intent.getAction())) {
            return super.onStartCommand(intent, flags, startId);
        }
        String state = intent.getStringExtra(STATE);
        String phoneNo = intent.getStringExtra(Intent.EXTRA_PHONE_NUMBER);
        log("state: " + state + " phoneNo: " + phoneNo);
        if (OUTGOING.equals(state)) {
            fileNamePrefix = getContactName(this.getContext(), phoneNo)
                    + OUTGOING_CALL_SUFFIX;
        } else if (INCOMING.equals(state)) {
            fileNamePrefix = getContactName(this.getContext(), phoneNo)
                    + INCOMING_CALL_SUFFIX;
        } else if (BEGIN.equals(state)) {
            startRecording();
        } else if (END.equals(state)) {
            stopRecording();
        } else if (STORAGE.equals(state)) {
            String mountState = Environment.getExternalStorageState();
            if (Environment.MEDIA_MOUNTED.equals(mountState)) {
                prepareAmrDir();
            } else {
                isMounted = false;
            }
            if (!isInRecording) {
                stopSelf();
            }
        }
        return START_STICKY;
    }

    public Context getContext() {
        return cntx;
    }

    private void stopRecording() {
        if (isInRecording) {
            isInRecording = false;
            recorder.stop();
            recorder.release();
            recorder = null;
            releaseWakeLock();
            stopSelf();
            log("call recording stopped");
        }
    }

    private String getDateTimeString() {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd'_'HHmmss");
        Date now = new Date();
        return sdf.format(now);
    }

    private String getMonthString() {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMM");
        Date now = new Date();
        return sdf.format(now);
    }

    private String getDateString() {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
        Date now = new Date();
        return sdf.format(now);
    }

    private String getTimeString() {
        SimpleDateFormat sdf = new SimpleDateFormat("HHmmss");
        Date now = new Date();
        return sdf.format(now);
    }

    private void startRecording() {
        if (!isMounted)
            return;
        stopRecording();
        try {
            File amr = new File(Environment.getExternalStorageDirectory()
                    .getAbsolutePath()
                    + AMR_DIR
                    + getDateTimeString()
                    + "_"
                    + fileNamePrefix + ".amr");
            log("Prepare recording in " + amr.getAbsolutePath());
            recorder = new MediaRecorder();
            recorder.setAudioSource(MediaRecorder.AudioSource.MIC);
            recorder.setOutputFormat(MediaRecorder.OutputFormat.THREE_GPP);
            recorder.setAudioEncoder(MediaRecorder.AudioEncoder.AMR_NB);
            recorder.setOutputFile(amr.getAbsolutePath());
            recorder.prepare();
            recorder.start();
            isInRecording = true;
            acquireWakeLock();
            log("Recording in " + amr.getAbsolutePath());
        } catch (Exception e) {
            Log.w(TAG, e);
        }
    }

    private void prepareAmrDir() {
        isMounted = Environment.getExternalStorageState().equals(
                Environment.MEDIA_MOUNTED);
        if (!isMounted)
            return;
        File amrRoot = new File(Environment.getExternalStorageDirectory()
                .getAbsolutePath() + AMR_DIR);
        if (!amrRoot.isDirectory())
            amrRoot.mkdir();
    }

    private String getContactName(Context cntx, String phoneNo) {
        if (null == phoneNo)
            return "";
        Uri uri = Uri.withAppendedPath(PhoneLookup.CONTENT_FILTER_URI,
                Uri.encode(phoneNo));
        ContentResolver cr = cntx.getContentResolver();
        Cursor c = cr.query(uri, new String[] { PhoneLookup.DISPLAY_NAME },
                null, null, null);
        if (null == c) {
            log("getContactName: The cursor was null when query phoneNo = "
                    + phoneNo);
            return phoneNo;
        }
        try {
            if (c.moveToFirst()) {
                String name = c.getString(0);
                name = name.replaceAll("(\\||\\\\|\\?|\\*|<|:|\"|>)", "");
                log("getContactName: phoneNo: " + phoneNo + " name: " + name);
                return name;
            } else {
                log("getContactName: Contact name of phoneNo = " + phoneNo
                        + " was not found.");
                return phoneNo;
            }
        } finally {
            c.close();
        }
    }

    private void log(String info) {
        if (DEBUG && isMounted) {
            File log = new File(Environment.getExternalStorageDirectory()
                    .getAbsolutePath()
                    + AMR_DIR
                    + "log_"
                    + getMonthString()
                    + ".txt");
            try {
                BufferedWriter out = new BufferedWriter(new FileWriter(log,
                        true));
                try {
                    synchronized (out) {
                        out.write(getDateString()+getTimeString());
                        out.write(" ");
                        out.write(info);
                        out.newLine();
                    }
                } finally {
                    out.close();
                }
            } catch (IOException e) {
                Log.w(TAG, e);
            }
        }
    }

    private void acquireWakeLock() {
        if (wakeLock == null) {
            log("Acquiring wake lock");
            PowerManager pm = (PowerManager) getSystemService(Context.POWER_SERVICE);
            wakeLock = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, this
                    .getClass().getCanonicalName());
            wakeLock.acquire();
        }

    }

    private void releaseWakeLock() {
        if (wakeLock != null && wakeLock.isHeld()) {
            wakeLock.release();
            wakeLock = null;
            log("Wake lock released");
        }

    }
}

//isServiceRunning

private boolean isServiceRunning() {
        ActivityManager myManager = (ActivityManager) getSystemService(Context.ACTIVITY_SERVICE);
        ArrayList<RunningServiceInfo> runningService = (ArrayList<RunningServiceInfo>) myManager
                .getRunningServices(30);
        for (int i = 0; i < runningService.size(); i++) {
            if (runningService.get(i).service.getClassName().equals(
                    MainService.class.getName())) {
                return true;
            }
        }
        return false;
    }

关于java - Android TTS如何在textview中显示说话的单词,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45234658/

相关文章:

c# - 我对 button.Click 事件有一些问题

java - 如何从 MethodArgumentNotValidException 类中提取字段名称和错误消息?

java - 如何扩展抽象泛型抽象接口(interface)?

java - 将 UUID 作为 blob 转换为正确的字符串 id hibernate

android - 在 headless (headless) linux 机器上运行 android 模拟器

所有浏览器中具有相同行高的按钮

java - 获取文件元数据字段

java - 编译运行时出错[NoClassDefFoundError]

java - 如何通过 SQLite 在 Android 中使用 double

html - CSS 悬停属性