Provides voice search capabilities using the Web Speech API, allowing users to perform searches using voice input.
Usage
import instantsearch from 'instantsearch.js';
import { voiceSearch } from 'instantsearch.js/es/widgets';
const search = instantsearch({
indexName: 'instant_search',
searchClient
});
search.addWidgets([
voiceSearch({
container: '#voice-search'
})
]);
search.start();
Parameters
container
string | HTMLElement
required
CSS selector or HTMLElement to insert the widget.
If true, searches are triggered on every transcription update. If false, only searches when speech recognition is complete.
The language to use for speech recognition. Uses the browser’s language by default.Example: 'en-US', 'fr-FR', 'es-ES'
additionalQueryParameters
Function to return additional query parameters based on the voice input.(params: { query: string }) => SearchParameters | void
Function to customize the voice search helper creation. For advanced use cases.
Templates to use for the widget.
Template for the button text. Receives voice search state.
Template for the status message. Receives voice search state including isListening, transcript, isSpeechFinal, errorCode.
CSS classes to add to the widget elements.
CSS class to add to the root element.
CSS class to add to the button element.
CSS class to add to the status element.
Examples
Basic voice search
voiceSearch({
container: '#voice-search',
searchAsYouSpeak: false
});
Search as you speak
voiceSearch({
container: '#voice-search',
searchAsYouSpeak: true,
language: 'en-US'
});
Custom templates
voiceSearch({
container: '#voice-search',
templates: {
buttonText({ isListening }) {
return isListening ? 'Stop' : 'Start voice search';
},
status({ transcript, isSpeechFinal, errorCode }) {
if (errorCode) {
return `Error: ${errorCode}`;
}
if (isSpeechFinal) {
return `Searching for: ${transcript}`;
}
return transcript ? `Listening: ${transcript}` : 'Click to speak';
}
}
});
With additional query parameters
voiceSearch({
container: '#voice-search',
additionalQueryParameters({ query }) {
return {
queryLanguages: ['en']
};
}
});
HTML output
<div class="ais-VoiceSearch">
<button class="ais-VoiceSearch-button">
Start voice search
</button>
<div class="ais-VoiceSearch-status">
Click to speak
</div>
</div>
Browser compatibility
This widget requires the Web Speech API, which is supported in:
- Chrome 25+
- Edge 79+
- Safari 14.1+
- Opera 27+
The widget will indicate when the browser doesn’t support voice search.