안드로이드 음성 인식과 텍스트로의 텍스트가 쉽게 만들어졌습니다.
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 가 항상 LinearLayout 내부에있어 제대로 작동하는 것이 중요합니다. 막대 높이 설정에 따라 너비와 높이를 조정할 수 있습니다 (아래 참조).
그런 다음 음성 인식을 시작하면 SpeechProgressView 통과합니다.
Speech . getInstance (). startListening ( speechProgressView , speechDelegate );원하는대로 5 개의 바 색상을 모두 설정할 수 있습니다. 이것은 단지 예입니다.
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" );
}
});스피치 인스턴스에서 세터 메소드를 사용하여 다양한 매개 변수를 구성 할 수 있으며 코드의 어느 곳에서나 이와 같은 것을 얻을 수 있습니다.
Speech . getInstance ()완전한 참조는 Javadocs를 참조하십시오.
기본적으로 라이브러리 로깅이 비활성화됩니다. 호출하여 디버그 로그를 활성화 할 수 있습니다.
Logger . setLogLevel ( LogLevel . DEBUG );코드에서 원하는 곳. 디버그에서 꺼짐으로 디테일 레벨을 조정할 수 있습니다.
라이브러리 로거는 기본적으로 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 Speech.getInstance().getSupportedTextToSpeechVoices() Speech.getInstance().getSupportedSpeechToTextLanguages(listener) 데모 앱에서 전체 예제를 확인하십시오.
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에게 감사드립니다.