2017-05-11 2 views
2

첫 번째 Android 앱을 만들기 위해 노력 중이며 작동하도록 텍스트를 가져올 수 없습니다.Android Studio에서 TextToSpeech 클래스 초기화

앱의 요점 : 사용자가 알람을 설정하려는 시간을 TimePicker를 사용하여 선택하면 앱에서 남은 시간을 계산하여 남은 시간을 지속적으로 업데이트합니다.

음성 엔진을 사용하여 5 분 간격으로 구두로 사용자를 업데이트하고 남은 시간을 알려주고 싶습니다.

모든 것이 컴파일되고 오류없이 실행되지만, 말하기 텍스트는 아무 것도하지 않습니다. 나는 자바에서 TextToSpeech 클래스를 제대로 초기화하는 방법을 찾기 위해 며칠 동안 찾았지만, 내가 찾은 모든 것은 상황에 따라 다르게 초기화하는 것으로 보인다.

여러 개의 다른 구현을 시도한 결과 모두 동일한 결과를 얻었으므로 편집하고 새로운 작업을 더 쉽게 시도하기 위해 별도의 내부 클래스를 만들기로 결정했으며 Voice 클래스를 만들고 메서드를 호출 할 수 있습니다.

저는 몇 달 동안 Java로 코딩을 해본 적이 있습니다. 이것이 내 첫 번째 Android 앱이므로,이 문제를 직접 해결하는 데 많은 어려움을 겪고 있습니다. 여기

private class Voice implements TextToSpeech.OnInitListener { 
    Context context = getApplicationContext(); 
    TextToSpeech tts = new TextToSpeech(context, this); 

    public void onInit(int initStatus) { 
     if (initStatus == TextToSpeech.SUCCESS) { 
      tts.setLanguage(Locale.US); 
     } 
    } 

    private void say(String announcement) { 
     tts.speak(announcement, TextToSpeech.QUEUE_FLUSH, null); 
    } 
} 

이 활동 코드의 나머지 부분 (나는를 표시하기 위해 별도의 활동을 사용할 수 있습니다 : 아래

내가 TextToSpeech 클래스를 초기화하는 데 사용하고 별도의 (중첩 된/내부) 클래스 카운트 다운)

import android.content.Context; 
import android.speech.tts.TextToSpeech; 
import android.support.v7.app.AppCompatActivity; 
import android.os.*; 
import android.widget.*; 
import java.util.*; 
import java.lang.*; 


public class TimerActivity extends AppCompatActivity{ 

private int alarmHour = MainActivity.alarmHour; 
private int alarmMinute = MainActivity.alarmMinute; 
private Calendar alarmTime; 
private Calendar currentTime; 
private TextView timerText; 
private TextView lateText; 
private int hoursLeft; 
private int minutesLeft; 
private long difference; 
private long calculatedMinutes; 
private boolean late = false; 
private String lateMessageString = "LATE!"; 
private String timeRemainingString = "remaining"; 
private Handler handler = new Handler(); 
private TextToSpeech tts; 
private double pitch = 1; 
private double speed = 1; 
private int MY_DATA_CHECK_CODE = 0; 
private Voice voice; 


@Override 
protected void onCreate(Bundle savedInstanceState) { 
    super.onCreate(savedInstanceState); 
    setContentView(R.layout.activity_timer); 
    voice = new Voice(); 
    voice.say("This is some bullshit."); 
    initializeTimer(); 
} 

private void initializeTimer() { 
    voice.say("Yes, hello. Is it me you're looking for?"); 
    timerText = (TextView) findViewById(R.id.timerText); 
    lateText = (TextView) findViewById(R.id.lateText); 
    setAlarm(); 
    calculateTimeLeft(); 
    String timerString = getTimerString(); 
    timerText.setText(timerString); 
    if (late) { 
     lateText.setText(lateMessageString); 
    } 
    else { 
     lateText.setText(timeRemainingString); 
    } 

    Timer timer = new Timer(); 
    timer.schedule(new UpdateTimer(),100,60000); 
} 



private class UpdateTimer extends TimerTask { 
    public void run() { 
     handler.post(new Runnable() { 
      public void run() { 
       calculateTimeLeft(); 
       String timerString = getTimerString(); 
       timerText.setText(timerString); 
       if (late) { 
        lateText.setText(lateMessageString); 
       } 
       else { 
        lateText.setText(timeRemainingString); 
       } 
      } 

     }); 
    } 
} 


private void setAlarm() { 
    alarmTime = Calendar.getInstance(); 
    currentTime = Calendar.getInstance(); 
    alarmTime.setTimeInMillis(System.currentTimeMillis()); 
    alarmTime.set(Calendar.HOUR_OF_DAY, alarmHour); 
    alarmTime.set(Calendar.MINUTE, alarmMinute); 
    // If alarm is set for the past, then set the alarm for the next day at the specified time 
    if (alarmTime.getTimeInMillis() - System.currentTimeMillis() < 0) { 
     alarmTime.set(Calendar.DAY_OF_YEAR, alarmTime.get(Calendar.DAY_OF_YEAR) + 1); 
    } 
} 

private void calculateTimeLeft() { 
    currentTime.setTimeInMillis(System.currentTimeMillis()); 
    difference = alarmTime.getTimeInMillis() - System.currentTimeMillis(); 
    long seconds = difference/1000; // convert to seconds 
    long calculatedHours = seconds/3600; // Find the number of hours until alarm 
    calculatedMinutes = (seconds % 3600)/60; // Use mod to remove the number of hours, leaving only seconds since the last hour, then divide by 60 to get minutes 

    hoursLeft = (int)Math.abs(calculatedHours); // Get the absolute value of the time left for the string 
    minutesLeft = (int)Math.abs(calculatedMinutes); // Absolute value of the minutes for string use 
} 

private String getTimerString() { 
    // Format the string showing the time remaining 
    String timeLeftString; 
    if (hoursLeft == 0) { 
     timeLeftString = ""; 
    } 
    else if (hoursLeft == 1) { 
     timeLeftString = hoursLeft + "hr "; 
    } 
    else { 
     timeLeftString = hoursLeft +"hrs "; 
    } 
    if (hoursLeft == 0) { 
     timeLeftString += minutesLeft; 
    } 
    /* 
    else if (minutesLeft < 10 && calculatedMinutes > 0) { 
     timeLeftString += "0" + minutesLeft; 
    } 
    */ 
    else { 
     timeLeftString += minutesLeft; 
    } 
    if (calculatedMinutes >= 0 && hoursLeft > 0) { 
     timeLeftString += " mins"; 
    } 
    else if (calculatedMinutes > 0) { 
     timeLeftString += " mins"; 
    } 
    else if (difference <= 0) { 
     late = true; 
    } 
    return timeLeftString; 
} 




private class Voice implements TextToSpeech.OnInitListener { 
    Context context = getApplicationContext(); 
    TextToSpeech tts = new TextToSpeech(context, this); 

    public void onInit(int initStatus) { 
     if (initStatus == TextToSpeech.SUCCESS) { 
      tts.setLanguage(Locale.US); 
     } 
    } 

    private void say(String announcement) { 
     tts.speak(announcement, TextToSpeech.QUEUE_FLUSH, null); 
    } 
} 

}

답변

0

은 당신이 원하는 목소리를들을 수 있다고 생각합니다.

TextToSpeech 클래스는 생성자를 호출 한 직후에 말할 수 없으므로

TextToSpeech 초기화 할 때 클래스 인스턴스가 시스템 TTS 서비스에 연결해야합니다.

인스턴스가 서비스에 연결하는 데 성공하면 onInitTextToSpeech.OnInitListener으로 활성화됩니다.

따라서 onInit 기능이 수행 된 후에 음성을들을 수 있습니다. onInit 기능에서 voice.say 기능을 이동하십시오.

private class Voice implements TextToSpeech.OnInitListener { 
    Context context = getApplicationContext(); 
    TextToSpeech tts = new TextToSpeech(context, this); 

    public void onInit(int initStatus) { 
     if (initStatus == TextToSpeech.SUCCESS) { 
      tts.setLanguage(Locale.US); 
      // try it! 
      voice.say("Can you hear this sentence?"); 
      // If you want to another "say", check this log. 
      // Your voice will say after you see this log at logcat. 
      Log.i("TAG", "TextToSpeech instance initialization is finished."); 
     } 
    } 

    private void say(String announcement) { 
     tts.speak(announcement, TextToSpeech.QUEUE_FLUSH, null); 
    } 
} 
관련 문제