For using webkitSpeechRecognition, a separate typescript service is being created along with its relevant unit test
The main idea to implement the voice search was
- To create an injectable speech service.
- Write methods for starting and stopping voice record in it.
- Import and inject the created speech service into root app module.
- Use the created speech service into required HomeComponent and FeedHeaderComponent.
Structure of Speech Service
The speech service mainly consists of two methods
- record() method which accepts lang as string input which specifies the language code for speech recording and returns a string Observable.
Using observe.complete() allows speech recognition action to stop when the user stops speaking.
- stoprecord() method which is used to stop the current instance of recording.
stop() method is used to stop the current instance of speech recognition.
Using Speech Service in required Component
In Loklak Search, the speech service have been included in two main components i.e. HomeComponent and FeedHeaderComponent. The basic idea of using the created speech service in these components is same.
In the TypeScript (not spec.ts) file of the two components, firstly import the SpeechService and create its object in constructor.
Secondly, define a speechRecognition() method and use the created instance or object of SpeechService in it to record speech and set the query as the recorded speech input. Here, default language has been set up as ‘en_US’ i.e. English.
After user clicks on speech icon, this method will be called and the recorded speech will be set as the query and there will be router navigation to the /search page where the result will be displayed.