A sobreposição de voz ajuda você a transformar a voz do usuário em texto , fornecendo uma experiência do usuário refinada e, ao mesmo tempo, gerenciando as permissões necessárias .
Utiliza internamente o SFSpeechRecognizer
nativo para realizar a conversão de fala em texto.
Você pode clonar e executar o projeto Demo fazendo pod install
e depois executando o projeto
O Swift Package Manager é uma ferramenta para gerenciar a distribuição de código Swift. Está integrado ao sistema de compilação Swift para automatizar o processo de download, compilação e vinculação de dependências.
Para usar o SwiftPM, você deve usar o Xcode 11+ para abrir seu projeto. Clique em File
-> Swift Packages
-> Add Package Dependency
e insira o URL do repositório InstantSearch VoiceOverlay.
Se você é um autor de estrutura e usa o VoiceOverlay como dependência, atualize seu arquivo 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á disponível através do CocoaPods. Para instalá-lo, adicione a seguinte linha ao seu Podfile:
pod 'InstantSearchVoiceOverlay' , '~> 1.1.0'
Carthage é um gerenciador de dependências simples e descentralizado para Cocoa.
Para instalar InstantSearchVoiceOverlay, adicione a seguinte linha ao seu Cartfile:
github "algolia/voice-overlay-ios" ~> 1.1 . 0
Info.plist
, adicione essas 2 propriedades de string junto com a descriçãoPrivacy - Microphone Usage Description
com uma descrição como: Need the mic for audio to text
Privacy - Speech Recognition Usage Description
com alguma descrição 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 ) ) " )
} )
}
Você pode personalizar sua sobreposição de voz modificando a propriedade settings
do 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...
Você pode alterar o local ou o SpeechController ao inicializar seu voiceOverlayController assim:
lazy var voiceOverlayController : VoiceOverlayController = {
let recordableHandler = {
return SpeechController ( locale : Locale ( identifier : " en_US " ) )
}
return VoiceOverlayController ( speechControllerHandler : recordableHandler )
} ( )
Você pode criar sua própria classe SpeechController personalizada implementando o protocolo Recordable
.
Observe que no Swift 4, você pode usar Locale.current.languageCode
para obter a localidade atual.
Opcionalmente, para ouvir texto e eventos de erro, você pode seguir o método do 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 ) " )
}
}
Quando faltam permissões, a sobreposição de voz guiará o usuário para a seção correta do aplicativo de configurações.
A tela de resultados aparece quando showResultScreen
está definido como verdadeiro.
/// 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 )
O widget fornece um resultScreenHandler
para quando a tela de resultados é descartada (desde que o botão "Iniciar novamente" não seja clicado). O manipulador fornece o texto que foi definido anteriormente em 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á disponível sob a licença do MIT. Consulte o arquivo LICENSE para obter mais informações.