La superposición de voz le ayuda a convertir la voz de su usuario en texto , proporcionando una experiencia de usuario pulida y gestionando los permisos necesarios .
Utiliza internamente el SFSpeechRecognizer
nativo para realizar la conversión de voz a texto.
Puede clonar y ejecutar el proyecto de demostración realizando pod install
y luego ejecutando el proyecto.
Swift Package Manager es una herramienta para gestionar la distribución de código Swift. Está integrado con el sistema de compilación Swift para automatizar el proceso de descarga, compilación y vinculación de dependencias.
Para usar SwiftPM, debe usar Xcode 11+ para abrir su proyecto. Haga clic en File
-> Swift Packages
-> Add Package Dependency
, ingrese la URL del repositorio de InstantSearch VoiceOverlay.
Si es autor de un marco y utiliza VoiceOverlay como dependencia, actualice su archivo Package.swift
:
let package = Package (
// 1.1.0 ..< 2.0.0
dependencies : [
. package ( url : " https://github.com/algolia/voice-overlay-ios " , from : " 1.1.0 " )
] ,
// ...
)
InstantSearchVoiceOverlay
está disponible a través de CocoaPods. Para instalarlo, agregue la siguiente línea a su Podfile:
pod 'InstantSearchVoiceOverlay' , '~> 1.1.0'
Carthage es un administrador de dependencias simple y descentralizado para Cocoa.
Para instalar InstantSearchVoiceOverlay, agregue la siguiente línea a su Cartfile:
github "algolia/voice-overlay-ios" ~> 1.1 . 0
Info.plist
, agregue estas 2 propiedades de cadena junto con la descripciónPrivacy - Microphone Usage Description
con una descripción como: Need the mic for audio to text
Privacy - Speech Recognition Usage Description
alguna descripción como: Need the speech recognition capabilities for searching tags
import InstantSearchVoiceOverlay
class ViewController : UIViewController {
let voiceOverlayController = VoiceOverlayController ( )
@ objc func voiceButtonTapped ( ) {
voiceOverlayController . start ( on : self , textHandler : { ( text , final ) in
print ( " voice output: ( String ( describing : text ) ) " )
print ( " voice output: is it final? ( String ( describing : final ) ) " )
} , errorHandler : { ( error ) in
print ( " voice output: error ( String ( describing : error ) ) " )
} )
}
Puede personalizar su superposición de voz modificando la propiedad settings
de voiceOverlayController:
/// Specifies whether the overlay directly starts recording (true),
/// or if it requires the user to click the mic (false). Defaults to true.
voiceOverlayController . settings . autoStart = true
/// Specifies whether the overlay stops recording after the user stops talking for `autoStopTimeout`
/// seconds (true), or if it requires the user to click the mic (false). Defaults to true.
voiceOverlayController . settings . autoStop = true
/// When autoStop is set to true, autoStopTimeout determines the amount of
/// silence time of the user that causes the recording to stop. Defaults to 2.
voiceOverlayController . settings . autoStopTimeout = 2
/// The layout and style of all screens of the voice overlay.
voiceOverlayController . settings . layout . < someScreen > . < someConstant >
// Use XCode autocomplete to see all possible screens and constants that are customisable.
// Examples:
/// The voice suggestions that appear in bullet points
voiceOverlayController . settings . layout . inputScreen . subtitleBulletList = [ " Suggestion1 " , " Sug2 " ]
/// Change the title of the input screen when the recording is ongoing.
voiceOverlayController . settings . layout . inputScreen . titleListening = " my custom title "
/// Change the background color of the permission screen.
voiceOverlayController . settings . layout . permissionScreen . backgroundColor = UIColor . red
/// And many more...
Puede cambiar la configuración regional o SpeechController al inicializar su voiceOverlayController de esta manera:
lazy var voiceOverlayController : VoiceOverlayController = {
let recordableHandler = {
return SpeechController ( locale : Locale ( identifier : " en_US " ) )
}
return VoiceOverlayController ( speechControllerHandler : recordableHandler )
} ( )
Puede crear su propia clase SpeechController personalizada implementando el protocolo Recordable
.
Tenga en cuenta que en Swift 4, puede usar Locale.current.languageCode
para obtener la configuración regional actual.
Opcionalmente, para escuchar texto y eventos de error, puede ajustarse al método del protocolo VoiceOverlayDelegate
.
// Second way to listen to recording through delegate
func recording ( text : String ? , final : Bool ? , error : Error ? ) {
if let error = error {
print ( " delegate: error ( error ) " )
}
if error == nil {
print ( " delegate: text ( text ) " )
}
}
Cuando faltan permisos, la superposición de voz guiará al usuario a la sección correcta de la aplicación de configuración.
La pantalla de resultados aparece cuando showResultScreen
se establece en verdadero.
/// Whether or not to show a result screen after the recording is finished.
voiceOverlayController . settings . showResultScreen = true
/// Timeout for showing the result screen in case no resultScreenText is provided on time.
voiceOverlayController . settings . showResultScreenTimeout = 2
/// Time for showing the result screen with the provided resultScreenText.
voiceOverlayController . settings . showResultScreenTime = 4
/// The processed result screen text that should be appear in the result screen.
voiceOverlayController . settings . resultScreenText = NSAttributedString ( string : myString , attributes : myAttributes )
El widget proporciona un resultScreenHandler
para cuando se cierra la pantalla de resultados (siempre que no se haga clic en el botón "Comenzar de nuevo"). El controlador proporciona el texto que se ha configurado de antemano en resultScreenText
.
voiceOverlayController . start ( on : self , textHandler : { ( text , final ) in
print ( " getting ( String ( describing : text ) ) " )
print ( " is it final? ( String ( describing : final ) ) " )
if final {
// Process the result to post in the result screen.
// The timer here simulates a network processing call that took 1.5 seconds.
Timer . scheduledTimer ( withTimeInterval : 1.5 , repeats : false , block : { ( _ ) in
let myString = text
let myAttribute = [ NSAttributedString . Key . foregroundColor : UIColor . red ]
let myAttrString = NSAttributedString ( string : myString , attributes : myAttribute )
self . voiceOverlayController . settings . resultScreenText = myAttrString
} )
}
} , errorHandler : { ( error ) in
print ( " error ( String ( describing : error ) ) " )
} , resultScreenHandler : { ( text ) in
print ( " Result Screen: ( text ) " )
} )
InstantSearchVoiceOverlay está disponible bajo la licencia MIT. Consulte el archivo de LICENCIA para obtener más información.