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的代碼審查,錯誤修復和圖書館改進的想法。