Flutter实时语音转文字插件aws_transcribe_streaming的使用

Flutter 实时语音转文字插件 aws_transcribe_streaming 的使用

开始使用

pubspec.yaml 文件中添加必要的依赖:

dependencies:
  aws_common: ^0.6.0
  aws_transcribe_streaming: ^0.1.0

获取 AWS IAM 用户的访问密钥和秘密密钥,该用户应具有 transcribe:StartStreamTranscription 权限。建议使用临时安全凭证,并在开始转录过程之前从后端获取会话令牌。

使用方法

  1. 创建一个新的转录流客户端:
import 'package:aws_common/aws_common.dart';
import 'package:aws_transcribe_streaming/aws_transcribe_streaming.dart';

final transcribeStreamingClient = TranscribeStreamingClient(
  region: 'eu-central-1',
  credentialsProvider: StaticCredentialsProvider(AWSCredentials(
    'ASIAIOEXAMPLEEXAMPLE',                       // 访问密钥ID
    'wJalrXUtnFEMI/K7MDENG/bPxRfiCYEXAMPLEKEY',   // 秘密访问密钥
    'AQoDYXdzEJr...',                             // 会话令牌
    DateTime.now().add(const Duration(hours: 1)), // 过期时间
  )),
);
  1. 启动流式转录:
final (response, audioStreamSink, transcriptEventStream) =
    await transcribeStreamingClient.startStreamTranscription(
  const StartStreamTranscriptionRequest(
    languageCode: LanguageCode.enUs,
    mediaSampleRateHertz: 48000,
    mediaEncoding: MediaEncoding.pcm,
  ),
);
  1. 订阅原始的 TranscriptEvent 流:
final transcriptSubscription = transcriptEventStream
    .listen((TranscriptEvent event) => print(event));

或者使用自定义策略来解码 TranscriptEvent 并构建实时转录:

final transcriptSubscription = transcriptEventStream
    .transform(const TranscriptEventStreamDecoder(PlainTextTranscriptionStrategy()))
    .listen((String message) => print(message));
  1. 开始发送音频数据到音频流接收器:
// 原始音频数据来自麦克风,采用PCM编码的16位小端字节流,采样率为48kHz
Stream<Uint8List> audioStream;

final audioStreamSubscription = audioStream.listen(
  audioStreamSink.add,
  onDone: audioStreamSink.close,
);

完整示例代码

import 'dart:async';
import 'dart:typed_data';

import 'package:aws_common/aws_common.dart';
import 'package:aws_transcribe_streaming/aws_transcribe_streaming.dart';

void main() async {
  // 创建一个客户端。
  final transcribeStreamingClient = TranscribeStreamingClient(
    region: 'eu-central-1',
    // 提供具有 `transcribe:StartStreamTranscription` 权限的凭证
    credentialsProvider: StaticCredentialsProvider(AWSCredentials(
      'ASIAIOEXAMPLEEXAMPLE', // 访问密钥ID
      'wJalrXUtnFEMI/K7MDENG/bPxRfiCYEXAMPLEKEY', // 秘密访问密钥
      'AQoDYXdzEJr...', // 会话令牌
      DateTime.now().add(const Duration(hours: 1)), // 过期时间
    )),
  );

  late final StartStreamTranscriptionResponse response;
  late final Stream<TranscriptEvent> transcriptEventStream;
  late final StreamSink<Uint8List> audioStreamSink;
  StreamSubscription<Uint8List>? audioStreamSubscription;

  try {
    // 启动流式转录。
    (response, audioStreamSink, transcriptEventStream) =
        await transcribeStreamingClient.startStreamTranscription(
      const StartStreamTranscriptionRequest(
        languageCode: LanguageCode.enUs,
        mediaSampleRateHertz: 48000,
        mediaEncoding: MediaEncoding.pcm,
      ),
    );
  } on TranscribeStreamingException catch (e) {
    print('Error starting transcription: $e');
    return;
  }

  print('Session ID: ${response.sessionId}');

  final transcriptionCompleter = Completer<void>();

  // 监听转录事件。
  // final transcriptSubscription =
  //     transcriptEventStream.listen((TranscriptEvent event) => print(event));
  // 或者使用自定义策略来解码转录事件。
  transcriptEventStream
      .transform(
          const TranscriptEventStreamDecoder(PlainTextTranscriptionStrategy()))
      .listen(
    (String message) {
      print('Transcription: $message');
    },
    onError: (Object error, StackTrace stackTrace) async {
      print('Transcription error: $error');
      await audioStreamSubscription?.cancel();
      await audioStreamSink.close();
    },
    onDone: () async {
      print('Transcription done');
      await audioStreamSubscription?.cancel();
      transcriptionCompleter.complete();
    },
  );

  // 而是使用来自麦克风的真实音频数据流
  // 采用PCM编码的16位小端字节流,采样率为48kHz。
  final audioStream = Stream<Uint8List>.periodic(
      const Duration(milliseconds: 200), (count) => Uint8List(19200)).take(25);

  // 发送音频数据到音频流接收器。
  audioStreamSubscription = audioStream.listen(
    audioStreamSink.add,
    onDone: audioStreamSink.close,
  );

  await transcriptionCompleter.future;

  print('Finished');
}

更多关于Flutter实时语音转文字插件aws_transcribe_streaming的使用的实战教程也可以访问 https://www.itying.com/category-92-b0.html

1 回复

更多关于Flutter实时语音转文字插件aws_transcribe_streaming的使用的实战系列教程也可以访问 https://www.itying.com/category-92-b0.html


当然,以下是如何在Flutter项目中使用aws_transcribe_streaming插件进行实时语音转文字的示例代码。请注意,你需要先确保已经在pubspec.yaml文件中添加了aws_transcribe_streaming依赖,并且已经配置好了AWS的认证信息。

1. 添加依赖

首先,在你的pubspec.yaml文件中添加aws_transcribe_streaming依赖:

dependencies:
  flutter:
    sdk: flutter
  aws_transcribe_streaming: ^latest_version  # 请替换为实际的最新版本号

然后运行flutter pub get来安装依赖。

2. 配置AWS认证

你需要配置AWS的认证信息,通常是通过AWS Amplify或者手动设置AWS凭证(如Access Key ID和Secret Access Key)。这里假设你已经配置好了AWS Amplify。

3. 使用aws_transcribe_streaming插件

以下是一个简单的示例,展示如何使用aws_transcribe_streaming插件进行实时语音转文字:

import 'package:flutter/material.dart';
import 'package:aws_transcribe_streaming/aws_transcribe_streaming.dart';
import 'package:speech_to_text/speech_to_text.dart' as stt; // 用于获取音频数据

void main() {
  runApp(MyApp());
}

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: TranscribeScreen(),
    );
  }
}

class TranscribeScreen extends StatefulWidget {
  @override
  _TranscribeScreenState createState() => _TranscribeScreenState();
}

class _TranscribeScreenState extends State<TranscribeScreen> {
  stt.SpeechToText _speechToText = stt.SpeechToText();
  AwsTranscribeStreaming? _transcribeStreaming;
  String _transcriptionText = '';

  @override
  void initState() {
    super.initState();
    initAwsTranscribeStreaming();
  }

  Future<void> initAwsTranscribeStreaming() async {
    // 初始化AWS Transcribe Streaming客户端
    _transcribeStreaming = AwsTranscribeStreaming(
      region: 'us-west-2',  // 替换为你的AWS区域
      accessKeyId: 'YOUR_ACCESS_KEY_ID',  // 替换为你的AWS Access Key ID
      secretAccessKey: 'YOUR_SECRET_ACCESS_KEY',  // 替换为你的AWS Secret Access Key
      sessionName: 'flutter-session',
    );

    // 监听转录结果
    _transcribeStreaming!.onTranscriptionResult!.listen((result) {
      setState(() {
        _transcriptionText = result.transcript;
      });
    });
  }

  Future<void> startTranscription() async {
    if (_speechToText.isListening) {
      return;
    }

    // 开始语音识别
    _speechToText.listen(
      onResult: (stt.SpeechRecognitionResult result) {
        // 将音频数据发送到AWS Transcribe Streaming
        final audioBytes = result.recognitionBytes!;
        _transcribeStreaming!.sendAudio(audioBytes);
      },
      onError: (e) {
        print('Speech to Text error: $e');
      },
      onListenStart: () {
        print('Listening...');
        // 开始AWS Transcribe Streaming会话
        _transcribeStreaming!.startSession();
      },
      onListenEnd: (stt.SpeechRecognitionResult result) {
        print('Stopped listening');
        // 结束AWS Transcribe Streaming会话
        _transcribeStreaming!.stopSession();
      },
      cancelOnError: true,
      listenFor: Duration(seconds: 30),
      pauseFor: Duration(seconds: 5),
      localeId: _speechToText.localeId,
    );
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('Flutter Real-time Speech to Text'),
      ),
      body: Padding(
        padding: const EdgeInsets.all(16.0),
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: <Widget>[
            Text(
              'Transcription:',
              style: TextStyle(fontSize: 20),
            ),
            SizedBox(height: 10),
            Text(
              _transcriptionText,
              style: TextStyle(fontSize: 18),
            ),
            SizedBox(height: 20),
            ElevatedButton(
              onPressed: startTranscription,
              child: Text('Start Transcription'),
            ),
          ],
        ),
      ),
    );
  }

  @override
  void dispose() {
    _speechToText.stop().then((_) {
      _speechToText.cancel();
    });
    _transcribeStreaming?.close();
    super.dispose();
  }
}

注意事项

  1. AWS凭证管理:不要在代码中硬编码AWS凭证。考虑使用环境变量或AWS Amplify等安全方式来管理凭证。
  2. 音频数据格式:确保发送到AWS Transcribe Streaming的音频数据格式符合其要求(如PCM格式)。
  3. 错误处理:示例代码中的错误处理较为简单,实际应用中应添加更完善的错误处理逻辑。
  4. 依赖冲突speech_to_text插件用于获取音频数据,但它可能与aws_transcribe_streaming插件在音频处理上有冲突,具体实现时可能需要调整。

希望这个示例能帮到你!

回到顶部