Voice Driven Web Apps: Introduction to the Web Speech API

文章推薦指數: 80 %
投票人數:10人

The new JavaScript Web Speech API makes it easy to add speech recognition to your web pages. This API allows fine control and flexibility over the speech ... Web Fundamentals Tools ChromeDevTools Lighthouse Puppeteer Workbox ChromeUserExperienceReport Updates CaseStudies Language English BahasaIndonesia Deutsch Español Français Português–Brasil Русский 中文–简体 日本語 한국어 Signin Updates Featured ByYear ByTag Web Fundamentals Tools More Updates Featured ByYear ByTag CaseStudies Capabilities WebUpdates(2021) AllArticles March AddingRankMagnitudetotheCrUXReportinBigQuery. WebUpdates(2020) AllArticles December DeprecationsandremovalsinChrome88 October DeprecationsandremovalsinChrome87Gainingsecurityandprivacybypartitioningthecache September DeprecationsandremovalsinChrome86 July AnewdefaultReferrer-PolicyforChrome:strict-origin-when-cross-originDeprecationsandremovalsinChrome85UsingCustomTabswithAndroid11 May DeprecationsandremovalsinChrome84HandlingHeavyAdInterventions April DeprecationsandremovalsinChrome83 February DeprecationsandremovalsinChrome81AddingnotificationpermissiondatatotheChromeUserExperienceReport WebUpdates(2019) AllArticles December DeprecationsandremovalsinChrome80WebVR1.1removedfromChrome October DeprecationsandremovalsinChrome79 September DeprecationsandremovalsinChrome78Fresherserviceworkers,bydefault August DeprecationsandremovalsinChrome77 July WebComponentsupdate:moretimetoupgradetov1APIs June DeprecationsandremovalsinChrome76UpdatingWebAPKsMoreFrequentlyAddressBarInstallforProgressiveWebAppsontheDesktopLayoutNGHowdoInotifyusersthatmyPWAisinstallable? May InChrome76youcanhidetheAddtoHomescreenmini-infobarAugmentedrealitywithmodel-viewerPaintHolding-reducingtheflashofwhiteonsame-originnavigationsDeprecationsandremovalsinChrome75Low-latencyrenderingwiththedesynchronizedhint March DeprecationsandremovalsinChrome74KVStorage:theWeb'sFirstBuilt-inModule February WebDevEcosystemteam-FebruarywrapupExploringaback/forwardcacheforChromeReplacingahotpathinyourapp'sJavaScriptwithWebAssemblyGetReadyforPriorityHintsConstructableStylesheets:seamlessreusablestylesDeprecationsandremovalsinChrome73MakingwheelscrollingfastbydefaultBettermatchresultswithString.prototype.matchAll()Themodel-viewerwebcomponentRenderingontheWebLightning-fasttemplates&WebComponents:lit-html&LitElement January RTCQuicTransportComingtoanOriginTrialNearYou(Chrome73)PrototypingStackPacksforLighthouseEmscriptenandnpmMakinguseractivationconsistentacrossAPIs WebUpdates(2018) AllArticles December DeprecationsandremovalsinChrome72IntroducingBackgroundFetch November WebAudio,AutoplayPolicyandGamesUnlockingnewcapabilitiesforthewebSignedHTTPExchanges October WebAssemblyThreadsreadytotryinChrome70DeprecationsandremovalsinChrome71WatchvideousingPicture-in-PictureTweakstocache.addAll()andimportScripts()cominginChrome71Chrome69PaintTimingIssuesHoudini'sAnimationWorklet September Insidelookatmodernwebbrowser(part4)Insidelookatmodernwebbrowser(part3)Audio/VideoUpdatesinChrome70DeprecationsandremovalsinChrome70Insidelookatmodernwebbrowser(part2)AsynchronousAccesstoHTTPCookiesInsidelookatmodernwebbrowser(part1)TheReportingAPI August ExtendingthebrowserwithWebAssemblyWebPerformanceMadeEasy:GoogleI/O2018editionEmscripten’sembindOffscreenCanvas—SpeedupYourCanvasOperationswithaWebWorkerCustomsiteperformancereportswiththeCrUXDashboard July ReportingObserver:knowyourcodehealthSpeedisnowalandingpagefactorforGoogleSearchandAdsPageLifecycleAPIIntroducingNoStatePrefetchPWACompat:theWebAppManifestforallbrowsersSiteIsolationforwebdevelopersExperimentingwithFirstInputDelayintheChromeUXReport June IntroductiontoFeaturePolicyMorenativeechocancellation!AudioWorkletDesignPatternAugmentedrealityforthewebChacmool:AugmentedrealityinChromeCanaryDeprecationsandremovalsinChrome68ChangestoAddtoHomeScreenBehavior May BeyondSPAs:alternativearchitecturesforyourPWAEnablingStrongAuthenticationwithWebAuthnWelcometotheimmersivewebUsingLighthouseToImprovePageLoadPerformanceAnnouncingLighthouse3.0 April DeprecationsandremovalsinChrome67LoadingWebAssemblymodulesefficientlyPresentwebpagestosecondaryattacheddisplays March WorkingwiththenewCSSTypedObjectModelDeprecationsandremovalsinChrome66macOSnativeechocancellation#SmooshGateFAQCredentialManagementAPIFeatureDetectionCheck-upEmscriptingaClibrarytoWasm February Lighthouse2.8UpdatesDeprecationsandremovalsinChrome65Meltdown/Spectre January ChromeUserExperienceReport:NewcountrydimensionCSSPaintAPI WebUpdates(2017) AllArticles December DisablinghardwarenoisesuppressionAnupdateonBetterAdsEnterAudioWorkletPreloadingmodulesChrome64todeprecatethechrome.loadTimes()APIChromeUserExperienceReport:expandingtotop1Million+originsDeprecationsandremovalsinChrome64Lighthouse2.6UpdatesTheDeviceMemoryAPI November Takecontrolofyourscroll:customizingpull-to-refreshandoverfloweffects October Removing::shadowand/deep/inChrome63DeprecationsandremovalsinChrome63ExceedingthebufferingquotaLighthouse2.5UpdatesAnimatingaBlur September AbortablefetchWebVRchangesinChrome62AneventforCSSposition:stickyDeprecationsandRemovalsinChrome62Picture-in-Picture(PiP)IntroducingvisualViewport August DeprecationsandRemovalsinChrome61EstimatingAvailableStorageSpace July Audio/VideoUpdatesinChrome61Upcomingregularexpressionfeatures June AlignedInputEventsSuperchargedLiveStreamBlog:CodeSplittingDOMException:Theplay()requestwasinterruptedAutomatedtestingwithHeadlessChromeLatestUpdatestotheCredentialManagementAPIDeprecationsandRemovalsinChrome60IntroductiontotheBudgetAPI May DeprecationsandRemovalsinChrome59 April GettingStartedwithHeadlessChromeMovingtotheNativeNotificationSystemonmacOS March ChromiumpolicyonJavaScriptdialogsBuildingperformantexpand&collapseanimationsCSSDeep-Dive:matrix3d()ForaFrame-PerfectCustomScrollbarAudio/VideoUpdatesinChrome58We'llCrossthe(Media)Streams,RayDeprecationsandRemovalsinChrome58BackgroundTabsinChrome57What'sNewInDevTools(Chrome58) February SpeedupServiceWorkerwithNavigationPreloadsLighthouseJanuary2017updateCustomizeMediaNotificationsandHandlePlaylistsAPIDeprecationsandRemovalsinChrome57 January ChangesinthePaymentRequestAPICSSGrid–Tablelayoutisback.Bethereandbesquare.MakingtouchscrollingfastbydefaultWebComponentsv1-thenextgeneration WebUpdates(2016) AllArticles December BuildingaBetterWebwithLighthouseURLBarResizingChromeDevTools:JavaScriptCPUProfilinginChrome58APIDeprecationsandRemovalsinChrome56position:stickyisbackinChromeTakePhotosandControlCameraSettingsPerformantParallaxing November GetReadyfortheChromeDevSummit2016 October AvoidingtheNotSecureWarninginChromeDevToolsDigest,October2016ManageHyphenswithCSSPointingtheWayForwardAPIDeprecationsandRemovalsinChrome55CaptureaMediaStreamFromaCanvas,VideoorAudioElementOnceUponanEventListenerTouchActionOptionsauxclickisComingtoChrome55Updatestodevelopers.google.com/web September Re-rasteringCompositedLayersonScaleChangeAPIDeprecationsandRemovalsinChrome54Cross-originServiceWorkers:ExperimentingwithForeignFetchCacheQueryOptionsArriveinChrome54DevToolsDigest,September2016:PerfRoundupOptionsofaPushSubscriptionBroadcastChannelAPI:AMessageBusfortheWeb August Interveningagainstdocument.write()WebAnimationsAPIHitsCross-browserMilestoneAPIDeprecationsandRemovalsinChrome53DevToolsDigest,August2016 July MutedAutoplayonMobile:SayGoodbyetoCanvasHacksandAnimatedGIFs!WebPushInteroperabilityWinsOfflineGoogleAnalyticsMadeEasyComplexitiesofanInfiniteScroller June GoodbyeShortSessions:AProposalforUsingServiceWorkerstoImproveCookieManagementontheWebECDSAforWebRTC:BetterSecurity,BetterPrivacyandBetterPerformanceFlexboxGetsNewBehaviorforabsolute-positionedChildrenServiceWorkerCaching,PlaybackRateandBlobURLsforAudioandVideoonChromeforAndroidCSSContainmentinChrome52APIDeprecationsandRemovalsinChrome52PerformanceObserver:EfficientAccesstoPerformanceDataDevToolsDigest:DevToolsin2016andBeyondImprovingScrollPerformancewithPassiveEventListenersStreamYourWaytoImmediateResponses May Houdini:DemystifyingCSS April DevToolsDigest:MorePowerwiththeNewCommandMenuGeolocationAPIRemovedfromUnsecuredOriginsinChrome50IntersectionObserver’sComingintoViewAPIDeprecationsandRemovalsinChrome51What’sNewwithKeyboardEvents?KeysandCodes!StreamliningtheSign-inFlowUsingCredentialManagementAPIExperimentTime:ScrollAnchoring March ANewDeviceModeforaMobile-FirstGenerationCreatingaWeb-EnabledIoTDevicewithIntelEdisonRemovingHeadachesfromFocusManagementMediaSourceAPI:AutomaticallyEnsureSeamlessPlaybackofMediaSegmentsinAppendOrderAPIDeprecationsandRemovalsinChrome50WebAnimationsImprovementsinChrome50CanvastoBlob()SupportAddedinChrome50ChromeSupportscreateImageBitmap()inChrome50DOMTokenListValidationAddedinChrome50FormDataMethodsforInspectionandModificationWebNotificationImprovementsinChrome50:Icons,CloseEvents,RenotifyPreferencesandTimestampsWebPushPayloadEncryptionDeviceOrientationChangesAreComingtoChrome50PrioritizingYourResourceswithlinkrel='preload'HTMLMediaElement.play()ReturnsaPromise February SuperchargedRemoteDebugging,ClassTogglesandOurOwnLateNightShow?!DevToolsGoDark,@keyframeEditingandSmarterAutocompleteWebAudioUpdatesinChrome49SmoothScrollinginChrome49IntroducingES2015ProxiesAPIDeprecationsandRemovalsinChrome49 January ControllingFontPerformancewithfont-displayCSSVariables:WhyShouldYouCare?RecordAudioandVideowithMediaRecorderVP9IsNowAvailableinWebRTCNotificationActionsinChrome48HighResolutionTimestampsforEventsEasyURLManipulationwithURLSearchParams WebUpdates(2015) AllArticles December GoogleCastforChromeonAndroidGettingStartedwithProgressiveWebAppsSecurityPanelDebutsinChromeDevToolsIntroducingBackgroundSync November Chrome47WebRTC:MediaRecording,SecureOriginsandProxyHandlingDevToolsDigest(CDSEdition):AGlimpseintotheFutureandRAILProfilingInstantLoadingWebAppswithanApplicationShellArchitecture October DevToolsDigest:EfficientElementEdits,ServiceWorkerDebugging,andMaterialDesignShadesWebAnimationsResourcesManagetheTriggeringofTouchtoSearchNotificationrequireInteraction-ASmootherNotificationUXonDesktopDevToolsDigest:TabReordering,Consoleis#2andFrameworkEventListenersInputDeviceCapabilitiesChooseCameras,MicrophonesandSpeakersfromYourWebApp September TheEMELoggerExtensionUpdatestotheServiceWorkerCacheAPIHistoryAPI:ScrollRestoration August AutomatingResourceSelectionwithClientHintsTabDiscardinginChrome:AMemory-SavingExperimentRollingoutPublicKeyPinningwithHPKPReportingUsingthewebappmanifesttospecifyasitewidethemecolorUsingrequestIdleCallbackThelarger-thanadvancedNetworkPanelfilter,andafewothersSimplekeyboardtrickstouseintheStylesPaneDevToolsDigest:AggregatedTimelineDetails,ColorPalettesandMoreNewReleaseofMaterialDesignLite-1.0.4UsingposterimagesonplugincontentEasilyduplicateDOMnodesEditHTMLintheConsolePanelFivetrickstouseintheConsolePanelAnewhomeforDevTools July ImprovedDOMbreadcrumbsLive-editCSSinSourcesDevToolsDigest:FilmstripandanewhomeforthrottlingAddanewcustomdeviceasapresetMediaStreamDeprecationsMeasuringPerformanceinaServiceWorkerUsingrotationAngleandtouchRadiusMediaplaybacknotificationsforChromeonAndroidInspectandtriggerCSSmediaqueriesShortcuttoselectthenextoccurrenceSelectandexecuteablockofcodeintheSourcesPanelSetabreakpointbasedonacertainconditionQuicklycyclethroughtheDevToolspanelsPrintoutaquickstacktracefromtheConsoleWhoinspectstheinspector?TriggerapseudoclassonanelementProjectwidesearchwithoptionalfilescopeNetworkcolorgroupsPreviewJavaScriptvaluesinlinewhiledebugging June Quicklyedit/viewresourcesfromtheElementspanelMediaSourceExtensionsforAudioHelpuserscheckoutfasterwithAutofill May NotifyingyouofChangestoNotificationsSomeUIandfeatureenhancementstotheColorPickertoolAlt+ClicktoexpandallchildnodesBetterIncognitoDevToolsCommandclicktoaddmultiplecursorsintheSourcesPanelCopyimageasdataURIQuick-editelementtagsQuicklymonitoreventsfromtheConsolePanelRevealinElementspanelSeematchingselectorsThecurrentlyselectedDOMnodeTheeasingeditorToggletheDevToolsdockstatewithakeyboardshortcutUnfinishednetworkrequestsUsekeyboardtonavigatethroughcallstackGetanddebugeventlistenersAutomaticallypauseonanyexceptionQuicklychangeCSSvaluesAutocompleteforbracketnotationReplayanetworkrequestincURLViewandchangeyourDOMbreakpointsScrollelementsintotheviewportFilmstripsinNetworkpanelTriggeringofpseudoclassesExpandCSSshorthandpropertiesPortforwardingSearchDOMtreebyCSSselectorGetnotifiedofJSerrorswhileyoutypeEasytimelinerecordingGotoalinenumberataspecificcolumnEasilyjumptoeventlistenersHighperformancevideowithhardwaredecodingGranularstatementhighlightsLocalModificationsHardreloadCyclethrougheditinglocationsCopytheresponseofanetworkresourcetoyourclipboardPerformacolumnselectionbybydragging April PredefinedsnippetsQuick-editelementtagsCopyimageasdataURIRevealinElementspanelSeematchingselectorsQuicklymonitoreventsfromtheConsolePanelCommandclicktoaddmultiplecursorsintheSourcesPanelBetterIncognitoDevToolsThecurrentlyselectedDOMnodeAlt+ClicktoexpandallchildnodesToggletheDevToolsdockstatewithakeyboardshortcutUnfinishednetworkrequestsTheeasingeditorAutocapitalizeformobileCutandCopyCommandsDOMAttributesnowontheprototypechainPermissionsAPIfortheWebSimplifiedConceptsinWebAnimationsNaming March AnewhomeforDevToolsDevToolsTimeline:NowProvidingtheFullStoryPushNotificationsontheOpenWebIntroductiontofetch()CreatingsemanticsiteswithWebComponentsandJSON-LD February Offline-first,fast,withthesw-precachemodule January GettingLiteralWithES6TemplateStringsChromeDevSummit2014:Let'sbuildsomeappswithPolymer!WhattheVirtualViewport?image-rendering:pixelatedChromeDevSummit2014:Polymer-StateoftheUnionChromeDevSummit2014:TheAppliedScienceofRuntimePerformance WebUpdates(2014) AllArticles December WebAnimationsPlaybackControlinChrome39FundamentalsofMobileWebDevelopment November Developerfeedbackneeded:FrameTimingAPISupportfortheme-colorinChrome39forAndroid October Generators:theGnarlyBitsSendbeacondatainChrome39 September PrecisionTouchforPreciseGestures August CollectingandIterating,theES6WayEasierArrayBuffertoStringconversionwiththeEncodingAPI July WebAudioChangesinm36dialogelementshippedinChrome37Beta June BlobsupportforIndexedDBlandedonChromeDevAutomatingWebPerformanceMeasurement May WebAnimations-element.animate()isnowinChrome36AMoreCompatible,SmootherTouch March GetontheCSSGrid! February TheYeomanMonthlyDigest#3 January YoPolymer–AWhirlwindTourOfWebComponentToolingWebappsthattalk-IntroductiontotheSpeechSynthesisAPIChromeDevSummit:PlatformsSummaryChromeDevSummit:OpenWebPlatformSummaryChromeDevSummit:PerformanceSummaryChromeDevSummit:Polymerdeclarative,encapsulated,reusablecomponentsChromeDevSummit:MobileSummary WebUpdates(2013) AllArticles December TheYeomanMonthlyDigest#2DevToolsDigestDecember2013NewWebAnimationsengineinBlinkdrivesCSSAnimations&Transitions300mstapdelay,goneaway November TheYeomanMonthlyDigest#1TheLandscapeOfFront-endDevelopmentAutomation(Slides) October WebAudioliveaudioinput-nowonAndroid!Flexboxlayoutisn'tslow September DevToolsanswers:Whatfontisthat?dialogelement:Modalsmadeeasy July AlphatransparencyinChromevideo June sourceMappingURLandsourceURLsyntaxchanged March IntroductiontoCustomFilters(akaCSSShaders)What'stheCSS:scopepseudo-classfor?VisualizingShadowDOMConcepts February ProfilingLongPaintTimeswithDevTools'ContinuousPaintingModeWebRTC:RTCDataChanneldemo,APIchanges...andChrometalkstoFirefox! January CSSBackgroundshorthandcomingtomobileWebKitbrowsersVoiceDrivenWebApps:IntroductiontotheWebSpeechAPI WebUpdates(2012) AllArticles December ScreensharingwithWebRTCCanvas-drivenbackgroundimagesWebRTChitsFirefox,AndroidandiOS November RespondtochangewithObject.observeContentSecurityPolicy1.0isofficiallyawesome. September InteractiveGlobewithCSSshaders&GoogleMapsLiveWebAudioInputEnabled!StackingChangesComingtoposition:fixedelements August Stickyourlandings!position:stickylandsinWebKitIntegratinginput[type=file]withtheFilesystemAPIWhenmillisecondsarenotenough:performance.now[datalist]forrange/colorinputsoffersomedefaultchoicesQuickFAQsoninput[type=date]inGoogleChrome July DraganddropafolderontoChromenowavailableHowtomeasurebrowsergraphicsperformanceArrived!xhr.send(ArrayBufferViews)TakingadvantageofGPUaccelerationinthe2DcanvasWritingaflippablebookusingCSSRegionsand3Dtransforms June TheamazingpowersofCSSHowtoconvertArrayBuffertoandfromStringDon'tBuildBlobs,ConstructThem May requestAnimationFrameAPI:nowwithsub-millisecondprecisionWebsocketFrameInspectionnowinChromeDevTools April datalistlandedinChromeCanaryProcessingXHR2fileuploadsinPHPWebRTCProtothonBigboosttoDOMperformance-WebKit'sinnerHTMLis240%fasterRound-upofWebBrowserInternalsResourcesTakinganEntirePageOfflineusingtheHTML5FileSystemAPI March CSSlayoutgetssmarterwithcalc()OptimizingJavaScriptANewExperimentalFeature:scopedstylesheets February WebGLandWebAudioAPIdemoroundupSwiftShaderbringssoftware3DrenderingtoChromeDetectDOMchangeswithMutationObserversGettingGmailtohandleallmailto:linkswithregisterProtocolHandlerChromeforAndroid:AcceleratingtheMobileWebPointerLockAPIBringsFPSGamestotheBrowserHTML5audioandtheWebAudioAPIareBFFs! January GettingRidofSynchronousXHRsWebAudioFAQIntroducingVideoPlayerSample WebUpdates(2011) AllArticles December CSSFilterEffectsLandinginWebKitTransferableObjects:LightningFast!UsemediumpprecisioninWebGLwhenpossible November ChromeDeveloperToolsforSpeed'Stream'videousingtheMediaSourceAPIWebGLdemoroundup October AppCacheToolsandAuto-GeneratorsDefiningScopeInIndexedDBTransactionsSpooktacularHTML5PumpkinLetYourContentDotheTalking:FullscreenAPIWebSocketsupdatedtolatestversioninChromeCanaryKeepingupwithHTML5andbrowsersupportHavingaridewithThree.js September NewGameConferenceforHTML5GameDevelopersCoupon7minutevideos:JavaScriptConsoleProtips&newishDOMAPIs August Workers♥ArrayBufferWhat'sdifferentinthenewWebSocketprotocolinsertAdjacentHTMLEverywhereDebuggingtheFilesystemAPISavinggeneratedfilesontheclient-sideSeekintolocalfileswiththeFileSystemAPIDownloadingresourcesinHTML5:a[download] July HTML5Libraries/polyfills-MidJulyAnnouncingNewGame,theconferenceforHTML5gamedevelopersDon'tMissaFrame:UsingthePageVisibilityAPI+HTML5VideoMultiplayerAudioFunUsingCross-domainimagesinWebGL June RegisteringacustomprotocolhandlerHTML5Libraries-LateJunePageVisibilityAPI:HaveIgotyourattention?ContrainHTML5+WebAudioAPInavigator.onLineinChromeDevchannelWelcometoupdates.html5rocks.com! ChromeDevTools Lighthouse Puppeteer Workbox ChromeUserExperienceReport ChromeDevSummitisback!Visitgoo.gle/cds2021tosecureyourspotinworkshops,officehoursandlearninglounges! Home Products Web Updates ByYear VoiceDrivenWebApps:IntroductiontotheWebSpeechAPI By Glen Shires GlenisacontributortoWebFundamentals ThenewJavaScriptWebSpeechAPImakesiteasytoaddspeechrecognitiontoyourwebpages.ThisAPIallowsfinecontrolandflexibilityoverthespeechrecognitioncapabilitiesinChromeversion25andlater.Here'sanexamplewiththerecognizedtextappearingalmostimmediatelywhilespeaking. DEMO/SOURCE Let’stakealookunderthehood.First,wechecktoseeifthebrowsersupportstheWebSpeechAPIbycheckingifthewebkitSpeechRecognitionobjectexists.Ifnot,wesuggesttheuserupgradestheirbrowser.(SincetheAPIisstillexperimental,it'scurrentlyvendorprefixed.)Lastly,wecreatethewebkitSpeechRecognitionobjectwhichprovidesthespeechinterface,andsetsomeofitsattributesandeventhandlers. if(!('webkitSpeechRecognition'inwindow)){ upgrade(); }else{ varrecognition=newwebkitSpeechRecognition(); recognition.continuous=true; recognition.interimResults=true; recognition.onstart=function(){...} recognition.onresult=function(event){...} recognition.onerror=function(event){...} recognition.onend=function(){...} ... Thedefaultvalueforcontinuousisfalse,meaningthatwhentheuserstopstalking,speechrecognitionwillend.Thismodeisgreatforsimpletextlikeshortinputfields.Inthisdemo,wesetittotrue,sothatrecognitionwillcontinueeveniftheuserpauseswhilespeaking. ThedefaultvalueforinterimResultsisfalse,meaningthattheonlyresultsreturnedbytherecognizerarefinalandwillnotchange.Thedemosetsittotruesowegetearly,interimresultsthatmaychange.Watchthedemocarefully,thegreytextisthetextthatisinterimanddoessometimeschange,whereastheblacktextareresponsesfromtherecognizerthataremarkedfinalandwillnotchange. Togetstarted,theuserclicksonthemicrophonebutton,whichtriggersthiscode: functionstartButton(event){ ... final_transcript=''; recognition.lang=select_dialect.value; recognition.start(); Wesetthespokenlanguageforthespeechrecognizer"lang"totheBCP-47valuethattheuserhasselectedviatheselectiondrop-downlist,forexample“en-US”forEnglish-UnitedStates.Ifthisisnotset,itdefaultstothelangoftheHTMLdocumentrootelementandhierarchy.Chromespeechrecognitionsupportsnumerouslanguages(seethe“langs”tableinthedemosource),aswellassomeright-to-leftlanguagesthatarenotincludedinthisdemo,suchashe-ILandar-EG. Aftersettingthelanguage,wecallrecognition.start()toactivatethespeechrecognizer.Onceitbeginscapturingaudio,itcallstheonstarteventhandler,andthenforeachnewsetofresults,itcallstheonresulteventhandler. recognition.onresult=function(event){ varinterim_transcript=''; for(vari=event.resultIndex;ior

.FinallyitsetsthesestringsastheinnerHTMLoftheircorrespondingelements:final_spanwhichisstyledwithblacktext,andinterim_spanwhichisstyledwithgraytext. interim_transcriptisalocalvariable,andiscompletelyrebuilteachtimethiseventiscalledbecauseit’spossiblethatallinterimresultshavechangedsincethelastonresultevent.Wecoulddothesameforfinal_transcriptsimplybystartingtheforloopat0.However,becausefinaltextneverchanges,we’vemadethecodehereabitmoreefficientbymakingfinal_transcriptaglobal,sothatthiseventcanstarttheforloopatevent.resultIndexandonlyappendanynewfinaltext. That’sit!Therestofthecodeistherejusttomakeeverythinglookpretty.Itmaintainsstate,showstheusersomeinformativemessages,andswapstheGIFimageonthemicrophonebuttonbetweenthestaticmicrophone,themic-slashimage,andmic-animatewiththepulsatingreddot. Themic-slashimageisshownwhenrecognition.start()iscalled,andthenreplacedwithmic-animatewhenonstartfires.Typicallythishappenssoquicklythattheslashisnotnoticeable,butthefirsttimespeechrecognitionisused,Chromeneedstoasktheuserforpermissiontousethemicrophone,inwhichcaseonstartonlyfireswhenandiftheuserallowspermission.PageshostedonHTTPSdonotneedtoaskrepeatedlyforpermission,whereasHTTPhostedpagesdo. Somakeyourwebpagescomealivebyenablingthemtolistentoyourusers! We’dlovetohearyourfeedback... ForcommentsontheW3CWebSpeechAPIspecification:email,mailingarchive,communitygroup ForcommentsonChrome’simplementationofthisspec:email,mailingarchive PleaserefertotheChromePrivacyWhitepapertolearnhowGoogleishandlingvoicedatafromthisAPI. Exceptasotherwisenoted,thecontentofthispageislicensedundertheCreativeCommonsAttribution4.0License,andcodesamplesarelicensedundertheApache2.0License.Fordetails,seetheGoogleDevelopersSitePolicies.JavaisaregisteredtrademarkofOracleand/oritsaffiliates. Lastupdated2019-03-12UTC. [{ "type":"thumb-down", "id":"missingTheInformationINeed", "label":"MissingtheinformationIneed" },{ "type":"thumb-down", "id":"tooComplicatedTooManySteps", "label":"Toocomplicated/toomanysteps" },{ "type":"thumb-down", "id":"outOfDate", "label":"Outofdate" },{ "type":"thumb-down", "id":"samplesCodeIssue", "label":"Samples/codeissue" },{ "type":"thumb-down", "id":"otherDown", "label":"Other" }] [{ "type":"thumb-up", "id":"easyToUnderstand", "label":"Easytounderstand" },{ "type":"thumb-up", "id":"solvedMyProblem", "label":"Solvedmyproblem" },{ "type":"thumb-up", "id":"otherUp", "label":"Other" }] ChromiumBlog ThelatestnewsontheChromiumblog. web.dev Usefulguidanceandanalysisfromweb.devforwebdevelopers. Twitter Connectwith@ChromiumDevonTwitter. Videos Checkoutourvideos. KeyTopics WebonAndroid ChromeExtensionDocs SiteKitpluginforWordPress Howtofileagoodbrowserbug ProgressiveWebApps MoreTopics SearchConsoleHelpCenter SearchConsoleCommunity Contribute FileanIssue ViewPageSource Android Chrome Firebase GoogleCloudPlatform Allproducts Terms Privacy SignupfortheGoogleDevelopersnewsletter Subscribe Language English BahasaIndonesia Deutsch Español Français Português–Brasil Русский 中文–简体 日本語 한국어



請為這篇文章評分?