Android TTS如何在textview

时间:2017-07-21 09:57:05

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

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

例如:如果TTS说这个字符串:你好!当它达到“如何”时,如何在文本视图中只显示单词“如何”。

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);
        }
    }

1 个答案:

答案 0 :(得分:0)

尝试阅读

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

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;

            }
        }
    }

// MainService

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;
    }