- 文字轉語音服務(TTS)應用
- 測試結果:點擊按鈕後將會聽到預設的聲音
public class MainActivity extends Activity{
private TextToSpeech tts;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState); setContentView(R.layout.activity_main);
tts=new TextToSpeech(this,new TTSListener());//初始化TTS,如果成功調用會聽到'TTS服務已上線'的語音 - }
private class TTSListener implements OnInitListener{
public void onInit(int status){
if (status==TextToSpeech.SUCCESS){//設置語言
int result=mtts.setLanguage(Locale.CHINA);//若返回-2即不支持該語言
if (result==TextToSpeech.LANG_MISSING_DATA||result==TextToSpeech.LANG_NOT_SUPPORTED){
Toast.makeText(this,"語言不可用,TTS使用失敗 ",Toast.LENGTH_LONG).show();}//若調用失敗會彈出提醒欄
else {
mtts.speak("TTS服務已上線", TextToSpeech.QUEUE_FLUSH,null);} } }
}
@Override
public void onClick(View v) {
// TODO Auto-generated method stub- //使用此種方法,需要在xml文件的各個button中添加 android:onClick="Click"
switch (view.getId()){
case R.id.button: - tts.speak("想要轉換爲語音的文字列", TextToSpeech.QUEUE_FLUSH, null);}
} }
xml佈局文件就很簡單:就一個button按鈕,
(PS:三星手機居然不支持日語,這就挺有意思
- 實現振動功能
首先需要在mainfest文件中加入聲明:
<uses-permission android:name="android.permission.VIBRATE"/>
final Vibrator vibrator=(Vibrator)getSystemService(VIBRATOR_SERVICE);
if (vibrator.hasVibrator()==true);//檢測硬件是否存振動系統
long[] vi_pattten={100,1000,200,2000}; vibrator.vibrate(vi_pattten,-1);
//使用函數,vi_patten爲可變long型,2個參數爲一組 第一爲等待ms啓動,第二爲持續時間
取消使用vibrator.cancel();
- 界面通知欄
Toast.makeText(File_listAc.this,"choose "+message,Toast.LENGTH_LONG).show();
參數介紹:1.通知欄在哪個界面顯示 2.要顯示的字符串 3.顯示模式(短時,長時) toast需要使用.show()纔可以顯示
- 頂部通知欄方法實例
protected void showNotification() {//頂部通知欄+震動
NotificationManager notificationManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
CharSequence title = "太陽系";
CharSequence contents = "三號行星";
PendingIntent contentIntent = PendingIntent.getActivity(this, 0,
new Intent(this, MainActivity.class), 0);
Notification notification = new Notification(R.drawable.default_icon,
title, System.currentTimeMillis());
notification.setLatestEventInfo(this, title, contents, contentIntent);//頂部通知欄內容,可修改
notificationManager.notify(NOTIFICATIONS_ID, notification);
}