如何使用 react-native 用音频通知用户?



我正在创建一个反应原生应用程序,它主要用于驾驶员,它具有此功能,可以在骑行时通过语音命令通知驾驶员,因为驾驶员正在骑行,因此他很难阅读测试通知。因此,我是移动应用程序开发的新手,在从Firebase服务器推送通知时需要音频解决方案。

我计划使用 TTS 库推送纯文本并将其转换为音频,我能够做到这一点,但是当应用程序处于非活动状态时,它不起作用。

我需要一个应该在ios/android中工作的解决方案,它可以播放音频文件或利用TTS在手机锁定时向用户传达消息,应用程序在后台运行。 如果即使应用程序不在后台运行时也可以做到这一点,那就太好了。

对于 android,您可以为此目的编写本机代码。 创建广播接收器 创建 TTS 服务 收到通知后,您可以发送广播。 从 BroadcastReceiver 中,您可以启动 TTS 服务作为意图。

public class TTS extends Service implements TextToSpeech.OnInitListener {
private TextToSpeech _testToSpeach;
@Override
public IBinder onBind(Intent arg0) {
return null;
}
@Override
public void onCreate() {
super.onCreate();
}
@Override
public void onDestroy() {
// TODO Auto-generated method stub
if (_testToSpeach != null) {
_testToSpeach.stop();
_testToSpeach.shutdown();
}
super.onDestroy();
}
@Override
public void onStart(Intent intent, int startId) {
_testToSpeach = new TextToSpeech(this, this);
speakOut();
}
@Override
public void onInit(int status) {
if (status == TextToSpeech.SUCCESS) {
int result = _testToSpeach.setLanguage(Locale.US);
if (result == TextToSpeech.LANG_MISSING_DATA
|| result == TextToSpeech.LANG_NOT_SUPPORTED) {
Log.e("TTS", "Language not supported");
}
speakOut();
} else {
Log.e("TTS", "Initilization Failed!");
}
}
private void speakOut() {
_testToSpeach.speak("its working", TextToSpeech.QUEUE_FLUSH, null);
}
}

你可以像这样从BroadcastReceiver启动TTS服务

context.startService(new Intent(context, TTS.class));

最新更新