TextToSpeech에서 텍스트를 음성으로 바꾸는 간단한 사용

2953 단어 android
오늘 데이터베이스 파일을 받았는데 그 안에 영어 단어의 음표가 많이 들어 있었다. 다른 사람의 소프트웨어가 음표를 표시할 수도 있고 단어를 낭독할 수도 있는 것을 보고 어떤 플러그인이 음표에 따라 발음할 수 있는지 생각했다. 나중에 많은 그룹에 물어봤는데 아무도 대답하지 않았다. 많은 자료를 찾아보니 이런 TTS가 있다는 것을 알게 되었다. 바로 텍스트를 음성으로 바꾸는 것이다.마침 안드로이드 도움말 문서 안에 Text To Speech가 있는 것을 보고 다른 사람과 도움말 문서를 탐색하는 테스트를 해봤는데 아니나 다를까 정말 읽을 수 있었다.부분 코드 및 주석:
main.xml



    

    

 MainAty.java

package fly.aty;

import java.util.Locale;

import android.app.Activity;
import android.os.Bundle;
import android.speech.tts.TextToSpeech;
import android.speech.tts.TextToSpeech.OnInitListener;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;

public class MainAty extends Activity implements OnClickListener, OnInitListener{

	private Button speechBtn; //         
	private TextView speechTxt; //        
	private TextToSpeech textToSpeech; // TTS  

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.main);

		speechBtn = (Button) findViewById(R.id.speechBtn);
		speechBtn.setOnClickListener(this);

		speechTxt = (TextView) findViewById(R.id.speechTxt);
		textToSpeech = new TextToSpeech(this, this); //   Context,TextToSpeech.OnInitListener
	}
	
	/**
	 *      TextToSpeech  
	 * status:SUCCESS ERROR 2  
	 * setLanguage    ,         22 
	 * TextToSpeech.LANG_MISSING_DATA:         。
	 * TextToSpeech.LANG_NOT_SUPPORTED:   
	 */
	@Override
	public void onInit(int status) {
		if (status == TextToSpeech.SUCCESS) {
			int result = textToSpeech.setLanguage(Locale.US);
			if (result == TextToSpeech.LANG_MISSING_DATA
					|| result == TextToSpeech.LANG_NOT_SUPPORTED) {
				Toast.makeText(this, "        ", Toast.LENGTH_SHORT).show();
			}
		}
	}

	@Override
	public void onClick(View v) {
		if (textToSpeech != null && !textToSpeech.isSpeaking()) {
			textToSpeech.setPitch(0.5f);//     ,       (  ),        ,1.0   
			textToSpeech.speak(speechTxt.getText().toString(),
					TextToSpeech.QUEUE_FLUSH, null);
		}
	}

	@Override
	protected void onStop() {
		super.onStop();
		textToSpeech.stop(); //         TTS    
		textToSpeech.shutdown(); //   ,    
	}
}

좋은 웹페이지 즐겨찾기