syncfusion-angular-speech-to-text

Compare original and translation side by side

🇺🇸

Original

English
🇨🇳

Translation

Chinese

Syncfusion Angular SpeechToText Component

Syncfusion Angular SpeechToText 组件

Component Overview

组件概述

The Syncfusion Angular SpeechToText component is a lightweight, accessible control that converts spoken words into text using the browser's native Speech Recognition API.
Key Capabilities:
  • Real-time Transcription - Convert speech to text with interim and final results
  • Button Customization - Configure icon, text, positioning, and styling for start/stop buttons
  • Tooltip Support - Add tooltips with custom content and positioning for better UX
  • Events & Interactions - Handle listening state changes, errors, and transcript updates
  • Methods - Programmatic control via startListening() and stopListening() methods
  • Language Support - Multi-language recognition with locale configuration
  • Globalization - RTL support and localization for international applications
  • Styling Options - CSS classes, HTML attributes, and theme integration
  • Security Features - HTTPS enforcement and explicit microphone permissions
  • Browser Compatibility - Chrome 25+, Edge 79+, Safari 12+, Opera 30+
Syncfusion Angular SpeechToText组件是一个轻量级、易访问的控件,它利用浏览器原生的Speech Recognition API将语音转换为文本。
核心功能:
  • 实时转录 - 支持临时和最终结果的语音转文本
  • 按钮自定义 - 配置开始/停止按钮的图标、文本、位置和样式
  • 提示框支持 - 添加自定义内容和位置的提示框,提升用户体验
  • 事件与交互 - 处理监听状态变化、错误和转录内容更新
  • 方法控制 - 通过startListening()和stopListening()方法实现程序化控制
  • 语言支持 - 支持多语言识别,可配置区域设置
  • 全球化 - 支持RTL(从右到左)布局与本地化,适配国际应用
  • 样式选项 - 支持CSS类、HTML属性和主题集成
  • 安全特性 - 强制HTTPS访问,需明确获取麦克风权限
  • 浏览器兼容性 - 支持Chrome 25+、Edge 79+、Safari 12+、Opera 30+

Documentation and Navigation Guide

文档与导航指南

Getting Started

快速入门

📄 Read: references/getting-started.md
  • Package installation (Ivy vs ngcc compatibility)
  • Angular project setup and configuration
  • CSS imports and theme management
  • Module imports and basic component rendering
  • Button content customization
  • Complete working example with TextArea integration
📄 阅读: references/getting-started.md
  • 包安装(Ivy与ngcc兼容性)
  • Angular项目搭建与配置
  • CSS导入与主题管理
  • 模块导入与基础组件渲染
  • 按钮内容自定义
  • 结合TextArea的完整示例

Button Customization

按钮自定义

📄 Read: references/button-customization.md
  • ButtonSettingsModel configuration
  • Start and stop button content labels
  • Icon customization with CSS classes
  • Icon positioning (top, bottom, left, right)
  • Primary button styling for emphasis
  • Visual style variations and best practices
📄 阅读: references/button-customization.md
  • ButtonSettingsModel配置
  • 开始与停止按钮的内容标签
  • 通过CSS类自定义图标
  • 图标位置(上、下、左、右)
  • 主按钮样式强调
  • 视觉样式变体与最佳实践

Tooltip Configuration

提示框配置

📄 Read: references/tooltip-configuration.md
  • TooltipSettingsModel setup
  • Tooltip content for start and stop states
  • Tooltip positioning relative to button
  • Enabling and disabling tooltips
  • Practical tooltip usage patterns
📄 阅读: references/tooltip-configuration.md
  • TooltipSettingsModel设置
  • 开始与停止状态的提示框内容
  • 提示框相对于按钮的位置
  • 启用/禁用提示框
  • 提示框实用使用模式

Styling and Appearance

样式与外观

📄 Read: references/styling-and-appearance.md
  • CSS class system (e-primary, e-outline, e-info, e-success, e-warning, e-danger)
  • Custom styling with cssClass property
  • Theme configuration and integration
  • HTML attributes customization
  • Custom CSS examples and advanced styling
📄 阅读: references/styling-and-appearance.md
  • CSS类系统(e-primary、e-outline、e-info、e-success、e-warning、e-danger)
  • 通过cssClass属性自定义样式
  • 主题配置与集成
  • HTML属性自定义
  • 自定义CSS示例与高级样式

Events and Methods

事件与方法

📄 Read: references/events-and-methods.md
  • Event types (created, onStart, onStop, onError, transcriptChanged)
  • Event handler implementation and event arguments (including event, name properties)
  • Programmatic control with startListening(), stopListening(), and destroy() methods
  • Controlling component state with listeningState property (Inactive, Listening, Stopped)
  • Canceling listening with the cancel property in onStart event
  • Distinguishing user vs programmatic actions with isInteracted property
  • Event handling patterns for different scenarios
  • Managing listening lifecycle programmatically
  • State transition management and workflow control
  • Component cleanup and memory management
📄 阅读: references/events-and-methods.md
  • 事件类型(created、onStart、onStop、onError、transcriptChanged)
  • 事件处理器实现与事件参数(包含event、name属性)
  • 通过startListening()、stopListening()和destroy()方法实现程序化控制
  • 通过listeningState属性控制组件状态(Inactive、Listening、Stopped)
  • 在onStart事件中使用cancel属性取消监听
  • 通过isInteracted属性区分用户触发与程序化触发
  • 不同场景的事件处理模式
  • 程序化管理监听生命周期
  • 状态转换管理与工作流控制
  • 组件清理与内存管理

Speech Recognition Features

语音识别功能

📄 Read: references/speech-recognition-features.md
  • Retrieving transcript from speech input
  • Setting recognition language (lang property)
  • Interim results configuration (allowInterimResults)
  • Listening state management (Inactive, Listening, Stopped)
  • Tooltip visibility control (showTooltip)
  • Disabled state configuration
  • State persistence with enablePersistence property
  • State monitoring and status management
  • Custom state management with localStorage
📄 阅读: references/speech-recognition-features.md
  • 从语音输入中获取转录文本
  • 设置识别语言(lang属性)
  • 临时结果配置(allowInterimResults)
  • 监听状态管理(Inactive、Listening、Stopped)
  • 提示框可见性控制(showTooltip)
  • 禁用状态配置
  • 通过enablePersistence属性实现状态持久化
  • 状态监控与状态管理
  • 结合localStorage实现自定义状态管理

Internationalization

国际化

📄 Read: references/internationalization.md
  • Localization setup using L10n.load()
  • Translation key mapping for error messages and labels
  • Multi-language implementation examples
  • RTL (Right-to-Left) support enablement
  • Language-specific configuration best practices
📄 阅读: references/internationalization.md
  • 使用L10n.load()设置本地化
  • 错误消息与标签的翻译键映射
  • 多语言实现示例
  • 启用RTL(从右到左)支持
  • 特定语言配置最佳实践

Security and Error Handling

安全与错误处理

📄 Read: references/security-and-error-handling.md
  • Security risks and mitigation strategies
  • Data transmission and privacy concerns
  • HTTPS enforcement and MITM prevention
  • Microphone permission management
  • Error type handling (no-speech, aborted, audio-capture, not-allowed, service-not-allowed, network, unsupported-browser, default)
  • Browser support matrix and compatibility
📄 阅读: references/security-and-error-handling.md
  • 安全风险与缓解策略
  • 数据传输与隐私问题
  • 强制HTTPS与中间人攻击预防
  • 麦克风权限管理
  • 错误类型处理(no-speech、aborted、audio-capture、not-allowed、service-not-allowed、network、unsupported-browser、default)
  • 浏览器支持矩阵与兼容性

Quick Start Example

快速入门示例

Here's a minimal working SpeechToText component with transcript output:
typescript
import { Component, ViewChild } from '@angular/core';
import { SpeechToTextModule, TextAreaComponent, TextAreaModule, TranscriptChangedEventArgs } from '@syncfusion/ej2-angular-inputs';

@Component({
    imports: [SpeechToTextModule, TextAreaModule],
    standalone: true,
    selector: 'app-root',
    template: `
    <div class="speechText-container">
        <button ejs-speechtotext 
                (transcriptChanged)="onTranscriptChange($event)">
        </button>
        <ejs-textarea #outputTextarea 
                      id="textareaInst" 
                      value="" 
                      rows="5" 
                      cols="50" 
                      resizeMode="None" 
                      placeholder="Transcribed text will be shown here...">
        </ejs-textarea>
    </div>`
})
export class AppComponent {
    @ViewChild('outputTextarea') outputTextarea!: TextAreaComponent;
    
    onTranscriptChange(args: TranscriptChangedEventArgs): void {
        this.outputTextarea.value = args.transcript;
    }
}
以下是带转录输出的最简SpeechToText组件工作示例:
typescript
import { Component, ViewChild } from '@angular/core';
import { SpeechToTextModule, TextAreaComponent, TextAreaModule, TranscriptChangedEventArgs } from '@syncfusion/ej2-angular-inputs';

@Component({
    imports: [SpeechToTextModule, TextAreaModule],
    standalone: true,
    selector: 'app-root',
    template: `
    <div class="speechText-container">
        <button ejs-speechtotext 
                (transcriptChanged)="onTranscriptChange($event)">
        </button>
        <ejs-textarea #outputTextarea 
                      id="textareaInst" 
                      value="" 
                      rows="5" 
                      cols="50" 
                      resizeMode="None" 
                      placeholder="Transcribed text will be shown here...">
        </ejs-textarea>
    </div>`
})
export class AppComponent {
    @ViewChild('outputTextarea') outputTextarea!: TextAreaComponent;
    
    onTranscriptChange(args: TranscriptChangedEventArgs): void {
        this.outputTextarea.value = args.transcript;
    }
}

Common Patterns

常见模式

Pattern 1: Customized Button with Events

模式1:带事件的自定义按钮

Implement a styled button with custom labels and event handlers:
typescript
public buttonSettings: ButtonSettingsModel = {
    content: 'Start Listening',
    stopContent: 'Stop Listening',
    iconCss: 'e-icons e-play',
    stopIconCss: 'e-icons e-pause',
    isPrimary: true
};

onListeningStart(args: StartListeningEventArgs): void {
    console.log('Listening started');
}

onListeningStop(args: StopListeningEventArgs): void {
    console.log('Listening stopped');
}
实现带自定义标签和事件处理器的样式化按钮:
typescript
public buttonSettings: ButtonSettingsModel = {
    content: 'Start Listening',
    stopContent: 'Stop Listening',
    iconCss: 'e-icons e-play',
    stopIconCss: 'e-icons e-pause',
    isPrimary: true
};

onListeningStart(args: StartListeningEventArgs): void {
    console.log('Listening started');
}

onListeningStop(args: StopListeningEventArgs): void {
    console.log('Listening stopped');
}

Pattern 2: Multi-Language Support

模式2:多语言支持

Configure localization for international applications:
typescript
L10n.load({
    'de': {
        "speech-to-text": {
            "startAriaLabel": "Drücken Sie, um zu sprechen",
            "stopAriaLabel": "Drücken Sie, um zu stoppen",
            "noSpeechError": "Keine Sprache erkannt"
        }
    }
});
为国际应用配置本地化:
typescript
L10n.load({
    'de': {
        "speech-to-text": {
            "startAriaLabel": "Drücken Sie, um zu sprechen",
            "stopAriaLabel": "Drücken Sie, um zu stoppen",
            "noSpeechError": "Keine Sprache erkannt"
        }
    }
});

Pattern 3: Programmatic Control

模式3:程序化控制

Manage listening state programmatically without user button clicks:
typescript
@ViewChild('speechtotext') speechToText!: SpeechToTextComponent;

public startListening(): void {
    this.speechToText.startListening();
}

public stopListening(): void {
    this.speechToText.stopListening();
}
无需用户点击按钮,程序化管理监听状态:
typescript
@ViewChild('speechtotext') speechToText!: SpeechToTextComponent;

public startListening(): void {
    this.speechToText.startListening();
}

public stopListening(): void {
    this.speechToText.stopListening();
}

Pattern 4: Error Handling

模式4:错误处理

Handle speech recognition errors gracefully:
typescript
onErrorHandler(args: ErrorEventArgs): void {
    if (args.error === 'no-speech') {
        console.log('No speech detected. Please try again.');
    } else if (args.error === 'not-allowed') {
        console.log('Microphone permission denied.');
    }
}
优雅处理语音识别错误:
typescript
onErrorHandler(args: ErrorEventArgs): void {
    if (args.error === 'no-speech') {
        console.log('No speech detected. Please try again.');
    } else if (args.error === 'not-allowed') {
        console.log('Microphone permission denied.');
    }
}

Pattern 5: Conditional Listening with Cancel

模式5:带取消功能的条件监听

Control when listening can start using the cancel property:
typescript
onListeningStart(args: StartListeningEventArgs): void {
    // Cancel listening if conditions aren't met
    if (!this.hasPermission || !navigator.onLine) {
        args.cancel = true;
        alert('Cannot start listening. Check permissions and connection.');
        return;
    }
    
    // Track if user or system triggered the action
    if (args.isInteracted) {
        console.log('User clicked the button');
    } else {
        console.log('Started programmatically');
    }
}
使用cancel属性控制监听是否可启动:
typescript
onListeningStart(args: StartListeningEventArgs): void {
    // 若条件不满足则取消监听
    if (!this.hasPermission || !navigator.onLine) {
        args.cancel = true;
        alert('Cannot start listening. Check permissions and connection.');
        return;
    }
    
    // 追踪触发源是用户还是系统
    if (args.isInteracted) {
        console.log('User clicked the button');
    } else {
        console.log('Started programmatically');
    }
}

Pattern 6: Distinguishing Interim vs Final Results

模式6:区分临时与最终结果

Handle interim and final transcripts differently:
typescript
onTranscriptChange(args: TranscriptChangedEventArgs): void {
    if (args.isInterimResult) {
        // Show interim results in real-time (lighter styling)
        this.interimText = args.transcript;
    } else {
        // Process final results (save, send to API, etc.)
        this.finalText = args.transcript;
        this.saveTranscript(args.transcript);
    }
}
差异化处理临时和最终转录文本:
typescript
onTranscriptChange(args: TranscriptChangedEventArgs): void {
    if (args.isInterimResult) {
        // 实时显示临时结果(浅色样式)
        this.interimText = args.transcript;
    } else {
        // 处理最终结果(保存、发送至API等)
        this.finalText = args.transcript;
        this.saveTranscript(args.transcript);
    }
}

Pattern 7: Controlling Component State

模式7:控制组件状态

Programmatically control the component's operational state:
typescript
import { SpeechToTextState } from '@syncfusion/ej2-angular-inputs';

export class AppComponent {
    public currentState: SpeechToTextState = SpeechToTextState.Inactive;
    
    // Set component to listening state
    startListening(): void {
        this.currentState = SpeechToTextState.Listening;
    }
    
    // Set component to stopped state
    stopListening(): void {
        this.currentState = SpeechToTextState.Stopped;
    }
    
    // Reset to inactive state
    resetState(): void {
        this.currentState = SpeechToTextState.Inactive;
    }
}
程序化控制组件的运行状态:
typescript
import { SpeechToTextState } from '@syncfusion/ej2-angular-inputs';

export class AppComponent {
    public currentState: SpeechToTextState = SpeechToTextState.Inactive;
    
    // 将组件设置为监听状态
    startListening(): void {
        this.currentState = SpeechToTextState.Listening;
    }
    
    // 将组件设置为停止状态
    stopListening(): void {
        this.currentState = SpeechToTextState.Stopped;
    }
    
    // 重置为非活跃状态
    resetState(): void {
        this.currentState = SpeechToTextState.Inactive;
    }
}

Pattern 8: Proper Component Cleanup

模式8:组件正确清理

Ensure proper cleanup to prevent memory leaks:
typescript
import { OnDestroy } from '@angular/core';

export class AppComponent implements OnDestroy {
    @ViewChild('speechtotext') speechToText!: SpeechToTextComponent;
    
    ngOnDestroy(): void {
        if (this.speechToText) {
            this.speechToText.stopListening();
            this.speechToText.destroy();
        }
    }
}
确保正确清理组件,防止内存泄漏:
typescript
import { OnDestroy } from '@angular/core';

export class AppComponent implements OnDestroy {
    @ViewChild('speechtotext') speechToText!: SpeechToTextComponent;
    
    ngOnDestroy(): void {
        if (this.speechToText) {
            this.speechToText.stopListening();
            this.speechToText.destroy();
        }
    }
}

Key Props

核心属性

PropTypeDefaultPurpose
buttonSettings
ButtonSettingsModel-Configure button appearance and labels
tooltipSettings
TooltipSettingsModel-Customize tooltip content and position
lang
string
'en-US'
Set speech recognition language
allowInterimResults
boolean
true
Enable real-time interim transcription
transcript
string
''
Current recognized text (read-only)
listeningState
SpeechToTextState
Inactive
Monitor listening status (Inactive, Listening, Stopped)
showTooltip
boolean
true
Display tooltip on hover
disabled
boolean
false
Disable component interaction
enablePersistence
boolean
false
Persist component state across page reloads
enableRtl
boolean
false
Enable right-to-left text direction
cssClass
string-Apply custom CSS classes
htmlAttributes
object-Set custom HTML attributes on button
locale
string
'en-US'
Set UI localization language
属性类型默认值用途
buttonSettings
ButtonSettingsModel-配置按钮外观与标签
tooltipSettings
TooltipSettingsModel-自定义提示框内容与位置
lang
string
'en-US'
设置语音识别语言
allowInterimResults
boolean
true
启用实时临时转录
transcript
string
''
当前识别的文本(只读)
listeningState
SpeechToTextState
Inactive
监控监听状态(Inactive、Listening、Stopped)
showTooltip
boolean
true
悬停时显示提示框
disabled
boolean
false
禁用组件交互
enablePersistence
boolean
false
页面刷新后保留组件状态
enableRtl
boolean
false
启用从右到左的文本方向
cssClass
string-应用自定义CSS类
htmlAttributes
object-为按钮设置自定义HTML属性
locale
string
'en-US'
设置UI本地化语言

Browser Requirements

浏览器要求

The SpeechToText component requires:
  • Active internet connection for speech recognition processing
  • Browser Speech Recognition API support:
    • Chrome 25+
    • Edge 79+
    • Safari 12+
    • Opera 30+
    • Firefox: Not Supported
  • Microphone hardware connected to the system
  • User microphone permission granted in browser settings
  • HTTPS context for secure microphone access (recommended)
SpeechToText组件需要满足以下条件:
  • 活跃的互联网连接:用于语音识别处理
  • 浏览器支持Speech Recognition API
    • Chrome 25+
    • Edge 79+
    • Safari 12+
    • Opera 30+
    • Firefox:不支持
  • 麦克风硬件:已连接至系统
  • 用户麦克风权限:已在浏览器设置中授予
  • HTTPS环境:推荐用于安全的麦克风访问