2017-07-21 37 views
0

如何在顯示單詞時將tts輸出顯示爲文本視圖。 其實我想在textview中顯示tts輸出的單詞。我有一個編輯文本,其中我輸入一些數據,然後當點擊播放按鈕時,它執行語音,但我也想在文本視圖中顯示說話的話,我該如何做到這一點,任何人都可以幫助我。我也考慮將文本轉換爲數組形式,然後通過,但我不認爲它有用任何其他解決方案? 我現在做的代碼。Android TTS如何在textview中顯示說出的單詞

例如:如果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); 
     } 
    } 

回答

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

這裏

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

// runAsForeground功能要在顯示的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; 
    } 
+0

sunil我不明白onClick方法可以詳細說明嗎? –

+0

只需在任意按鈕單擊監聽器中添加第一個代碼片段 –

+0

什麼是Intent i = new Intent(MainService.ACTION);如果(isServiceRunning())我不能解決它們 –