Android语音识别和语音文字变得容易。
implementation ' net.gotev:speech:x.y.z ' xyz
要开始使用库,您必须在活动中初始化它
public class YourActivity extends Activity {
Override
protected void onCreate ( Bundle savedInstanceState ) {
super . onCreate ( savedInstanceState );
setContentView ( R . layout . your_layout );
Speech . init ( this , getPackageName ());
}
@ Override
protected void onDestroy () {
// prevent memory leaks when activity is destroyed
Speech . getInstance (). shutdown ();
}
}您可以在examples目录中找到一个完整的演示应用程序,该应用程序使用此库。只需检查项目并尝试一下即可。
活动内部:
try {
// you must have android.permission.RECORD_AUDIO granted at this point
Speech . getInstance (). startListening ( new SpeechDelegate () {
@ Override
public void onStartOfSpeech () {
Log . i ( "speech" , "speech recognition is now active" );
}
@ Override
public void onSpeechRmsChanged ( float value ) {
Log . d ( "speech" , "rms is now: " + value );
}
@ Override
public void onSpeechPartialResults ( List < String > results ) {
StringBuilder str = new StringBuilder ();
for ( String res : results ) {
str . append ( res ). append ( " " );
}
Log . i ( "speech" , "partial result: " + str . toString (). trim ());
}
@ Override
public void onSpeechResult ( String result ) {
Log . i ( "speech" , "result: " + result );
}
});
} catch ( SpeechRecognitionNotAvailable exc ) {
Log . e ( "speech" , "Speech recognition is not available on this device!" );
// You can prompt the user if he wants to install Google App to have
// speech recognition, and then you can simply call:
//
// SpeechUtil.redirectUserToGoogleAppOnPlayStore(this);
//
// to redirect the user to the Google App page on Play Store
} catch ( GoogleVoiceTypingDisabledException exc ) {
Log . e ( "speech" , "Google voice typing must be enabled!" );
}在您的活动的onDestroy中,补充:
@ Override
protected void onDestroy () {
Speech . getInstance (). shutdown ();
}为了防止记忆泄漏。
将其添加到您的布局中:
< LinearLayout
android : orientation = " vertical "
android : layout_width = " wrap_content "
android : layout_height = " wrap_content "
android : id = " @+id/linearLayout " >
< net .gotev.speech.ui.SpeechProgressView
android : id = " @+id/progress "
android : layout_width = " 120dp "
android : layout_height = " 150dp " />
</ LinearLayout >重要的是, SpeechProgressView始终在线安装中以正常运行。您可以将宽度和高度相应地调整为条高度设置(请参见下文)。
然后,当您启动语音识别时,还可以通过SpeechProgressView :
Speech . getInstance (). startListening ( speechProgressView , speechDelegate );您可以根据需要设置所有5个bar颜色。这只是一个例子:
int [] colors = {
ContextCompat . getColor ( this , android . R . color . black ),
ContextCompat . getColor ( this , android . R . color . darker_gray ),
ContextCompat . getColor ( this , android . R . color . black ),
ContextCompat . getColor ( this , android . R . color . holo_orange_dark ),
ContextCompat . getColor ( this , android . R . color . holo_red_dark )
};
speechProgressView . setColors ( colors ); int [] heights = { 60 , 76 , 58 , 80 , 55 };
speechProgressView . setBarMaxHeightsInDp ( heights );活动内部:
Speech . getInstance (). say ( "say something" );您还可以提供回调以接收状态:
Speech . getInstance (). say ( "say something" , new TextToSpeechCallback () {
@ Override
public void onStart () {
Log . i ( "speech" , "speech started" );
}
@ Override
public void onCompleted () {
Log . i ( "speech" , "speech completed" );
}
@ Override
public void onError () {
Log . i ( "speech" , "speech error" );
}
});您可以通过使用语音实例上的setter方法来配置各种参数,您可以在代码中的任何地方获得这样的内容:
Speech . getInstance ()请参阅Javadocs以获取完整的参考。
默认情况下,库记录被禁用。您可以通过调用来启用调试日志:
Logger . setLogLevel ( LogLevel . DEBUG );无论您在代码中想要的地方。您可以调整从调试到OFF的细节级别。
库logger默认使用android.util.Log ,因此您将在LogCat中获取输出。如果要将日志重定向到不同的输出或使用其他记录仪,则可以提供自己的代表实现:
Logger . setLoggerDelegate ( new Logger . LoggerDelegate () {
@ Override
public void error ( String tag , String message ) {
//your own implementation here
}
@ Override
public void error ( String tag , String message , Throwable exception ) {
//your own implementation here
}
@ Override
public void debug ( String tag , String message ) {
//your own implementation here
}
@ Override
public void info ( String tag , String message ) {
//your own implementation here
}
});使用Speech.getInstance().getSpeechToTextLanguage()和Speech.getinstance().getTextToSpeechVoice() 。检查演示应用程序的完整示例。
使用Speech.getInstance().getSupportedSpeechToTextLanguages(listener)和Speech.getInstance().getSupportedTextToSpeechVoices() 。检查演示应用程序的完整示例。
使用Speech.getInstance().setLocale(locale)和Speech.getInstance().setVoice(voice) 。检查演示应用程序的完整示例。
当您设置语言环境时,语音会自动更改为该语言的默认语音。如果要设置特定的声音,请记住每次更改语言环境时都重新设置它。
感谢@zagum的原始实现语音识别视图。
Copyright (C) 2019 Aleksandar Gotev
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
感谢Kristiyan Petrov的代码审查,错误修复和图书馆改进的想法。