Android11 初始化失败问题处理
//初始化
new TextToSpeech(Context context, OnInitListener listener);
原因:Android11 软件包可见性问题导致TextToSpeech初始化失败,只需要在文件中增加<queries>标签即可
增加权限
...
<uses-permission android:name=".FOREGROUND_SERVICE"/>
<queries>
<intent>
<action android:name=".TTS_SERVICE" />
</intent>
</queries>
<application ...
Demo示例,实现一个读取输入文字的功能
布局文件xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:andro
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<EditText
android:
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="请输入要朗诵的字" />
<Button
android:
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="读" />
</LinearLayout>
代码:
package ;
import ;
import ;
import .;
import ;
import ;
import ;
import ;
import ;
public class MainActivity extends AppCompatActivity implements , {
private Button speechBtn; // 按钮控制开始朗读
private EditText speechTxt; // 需要朗读的内容
private TextToSpeech textToSpeech; // TTS对象
@Override
public void onCreate(Bundle savedInstanceState) {
(savedInstanceState);
setContentView(.activity_main);
speechBtn = (Button) findViewById(.btn_read);
(this);
speechTxt = (EditText) findViewById();
//初始化
textToSpeech = new TextToSpeech(this, this); // 参数Context,
}
/**
* 用来初始化TextToSpeech引擎
* status:SUCCESS或ERROR这2个值
* setLanguage设置语言,帮助文档里面写了有22种
* TextToSpeech.LANG_MISSING_DATA:表示语言的数据丢失。
* TextToSpeech.LANG_NOT_SUPPORTED:不支持
*/
@Override
public void onInit(int status) {
if (status == ) {
int result = ();
if (result == TextToSpeech.LANG_MISSING_DATA
|| result == TextToSpeech.LANG_NOT_SUPPORTED) {
(this, "数据丢失或不支持", Toast.LENGTH_SHORT).show();
}
} else {
("TTS", "Initilization Failed!");
}
}
@Override
public void onClick(View v) {
if (textToSpeech != null && !()) {
(0.0f);// 设置音调,值越大声音越尖(女生),值越小则变成男声,1.0是常规
(().toString(),
TextToSpeech.QUEUE_FLUSH, null);
}
}
@Override
protected void onStop() {
();
(); // 不管是否正在朗读TTS都被打断
(); // 关闭,释放资源
}
}