我有一个创建“音频”类的活动,并尝试使用 android Text to Speech API 来读取一些文本。如果该语言不受支持,它会尝试使用 MediaPlayer 从服务器播放自定义 mp3 文件。最后,如果 MediaPlayer 失败,它会使用 Nuance SpeechKit 来读取文本:
我的问题是当我销毁活动时,我也想销毁/停止 Nuance 音频,但我不确定如何关闭 Nuance 音频。
活动课
private Audio audio;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.my_layout);
audio = new Audio(this).play("my text to read");
}
@Override
protected void onPause() {
audio.pause();
super.onPause();
}
@Override
protected void onDestroy() {
audio.destroy();
super.onDestroy();
}
音频类
private TextToSpeech tts;
private MediaPlayer player;
private Session session;
public void play(String text) {
// check if supported
if (supported) tts.speak(text, TextToSpeech.QUEUE_FLUSH, null);
else mediaPlayer(text);
}
private void mediaPlayer(String text) {
// make some queries on server to find the file url
if (queryFoundFile) {
player = new MediaPlayer();
player.setDataSource(myFileUrl);
player.setAudioStreamType(3);
player.prepare();
player.start();
} else nuancePlayer(text);
}
private void nuancePlayer(String text) {
Transaction.Options options = new Transaction.Options();
options.setLanguage(new Language("eng-USA"));
session = Session.Factory.session(activity, myServer, appKey);
session.speakString(text, options, new Transaction.Listener() {
@Override
public void onError(Transaction transaction, String s, TransactionException e) {
e.printStackTrace()
}
});
// it reaches here and nuance plays the audio
}
// these are the methods I call when the activity is paused or destroyed
public void pause() {
if (tts != null) tts.stop();
if (player != null) player.stop();
if (nuance != null) nuance.getAudioPlayer().stop(); // don't work
}
public void destroy() {
if (tts != null) tts.shutdown();
if (player != null) player.release();
if (nuance != null) nuance.getAudioPlayer().stop(); // don't work
}
如果我使用 Text to Speech 或 MediaPlayer 并且我销毁了我的 Activity,则音频会立即被销毁。但如果正在播放 Nuance,我似乎无法破坏音频。它只是一直在说话。
我做了一些调试,并调用了 pause() 和 destroy() 方法。nuance.getAudioPlayer 也不为空,并且正在播放 AudioPlayer。当我对他调用方法 stop() 时,我找不到他没有停止的原因。
什么是细微差别?
这是我第一次使用 Nuance,所以我对此并不熟悉。基本上我认为它是 Android Text to Speech 的替代品。
为什么我的项目中有这个?
我的项目有 4 种主要语言,我需要一个文本到语音功能来阅读一些文本。问题是,android Text to Speech 不支持 Nuance 支持的其中一些语言。
为什么 Nuance 是我的最后选择?
因为 Nuance 有成本。我尝试使用 android TTS 或 MediaPlayer。只有当这两个失败时,我才会使用 Nuance。这是阅读我的文字的最后手段!