我正在开发一款需要文字转语音的应用。所以我读了几篇tts教程并做了这个:
public void buttonClick (View view) {
TextToSpeech tts = new TextToSpeech (this, new TextToSpeech.OnInitListener () {
@Override
public void onInit(int status) {
}
});
tts.setLanguage (Locale.UK);
tts.speak ("Hello World", TextToSpeech.QUEUE_FLUSH, null);
}
然而,当我运行应用程序并单击按钮时,没有听到任何声音,只有"单击"按钮的声音。这也意味着扬声器已开启。
我想这是因为speak(String, int, HashMap<String, String>)
已被弃用。当我查看文档时,这个猜测被证明是错误的:
/** @deprecated As of API level 21, replaced by
* {@link #speak(CharSequence, int, Bundle, String)}.
*/
我的应用程序的最低SDK版本是API18,我的设备的Android版本是Android 4.3。这意味着{@ 1}}不会被弃用。弃用可能只是Android Studio的一个错误。
我想知道为什么它没有声音以及如何解决这个问题。
答案 0 :(得分:1)
试试这个例子。
import android.app.Activity;
import android.hardware.SensorManager;
import android.os.Bundle;
import android.speech.tts.TextToSpeech;
import android.util.Log;
import android.view.Menu;
import android.view.View;
import android.widget.Button;
import java.util.List;
import java.util.Locale;
import android.hardware.Sensor;
import android.hardware.SensorManager;
import android.widget.Toast;
public class MainActivity extends Activity {
TextToSpeech t1;
Button b1;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
b1=(Button)findViewById(R.id.button);
t1=new TextToSpeech(getApplicationContext(), new TextToSpeech.OnInitListener() {
@Override
public void onInit(int status) {
if(status != TextToSpeech.ERROR) {
t1.setLanguage(Locale.UK);
}
}
});
b1.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
t1.speak("Hi dear its working", TextToSpeech.QUEUE_FLUSH, null);
}
});
}
public void onPause(){
if(t1 !=null){
t1.stop();
t1.shutdown();
}
super.onPause();
}
}
和xml文件是
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity"
android:transitionGroup="true">
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Text to Speech"
android:id="@+id/button"
android:layout_below="@+id/editText"
android:layout_centerHorizontal="true"
android:layout_marginTop="46dp" />
</RelativeLayout>
答案 1 :(得分:1)
public void buttonClick (View view) {
TextToSpeech tts = new TextToSpeech (this, new TextToSpeech.OnInitListener () {
@Override
public void onInit(int status) {
// change required.Initialization has to finish first.
if(status != TextToSpeech.ERROR) {
tts.setLanguage (Locale.UK);
tts.speak ("Hello World", TextToSpeech.QUEUE_FLUSH, null);
}
}
});
}