|
- import 'package:demo001/plugin/xunfei/audiotranslate/audiotranslate.dart';
- import 'package:demo001/plugin/xunfei/audiotranslate/result_audio.dart';
- import 'package:demo001/plugin/xunfei/audiotranslate/result_test.dart';
- import 'package:flutter/material.dart';
- import 'package:flutter/services.dart';
-
- class MyHomePage extends StatefulWidget {
- const MyHomePage({super.key, required this.title});
- final String title;
- @override
- State<MyHomePage> createState() => _MyHomePageState();
- }
-
- class _MyHomePageState extends State<MyHomePage> {
- late Xunfei_AudioTranslation xunfei;
- String _result = "";
- // 在 initState 中初始化
- @override
- void initState() {
- super.initState();
- xunfei = new Xunfei_AudioTranslation(
- appId: "137dc132",
- apiKey: "1c1891a475e71250ecd1320303ad6545",
- apiSecret: "MjZhNDA1NTI1NWZkZDQxOTMxYzMyN2Yw",
- onResponse: _onResponse,
- );
- }
-
- void _onResponse(Xunfei_AudioTranslation_Result_Text text,
- Xunfei_AudioTranslation_Result_Audio audio) {
- setState(() {
- _result = "接受消息:${text.result()}";
- });
- }
-
- //测试链接
- Future<void> _connectTest() async {
- await xunfei.start();
- setState(() {
- _result = "链接状态:${xunfei.state}";
- });
- }
-
- // 读取本地文件转流对象
- Stream<List<int>> _getAudioStream() async* {
- // 从 assets 中读取音频文件
- final byteData = await rootBundle.load('assests/original.pcm');
- final buffer = byteData.buffer.asUint8List();
-
- // 按块生成流,块大小为 frameSize
- int frameSize = 1280; // 每一帧的音频大小
- for (int i = 0; i < buffer.length; i += frameSize) {
- int end =
- (i + frameSize <= buffer.length) ? i + frameSize : buffer.length;
- yield buffer.sublist(i, end);
- }
- }
-
- //测试翻译
- Future<void> _translationTest() async {
- Stream<List<int>> audioStream = _getAudioStream();
- await xunfei.pushaudio(audioStream);
- }
-
- //测试录音
- void _recordTest() {}
-
- @override
- Widget build(BuildContext context) {
- return Scaffold(
- appBar: AppBar(
- backgroundColor: Theme.of(context).colorScheme.inversePrimary,
- title: Text(widget.title),
- ),
- body: Center(
- child: Column(
- mainAxisAlignment: MainAxisAlignment.center,
- children: <Widget>[
- const Text(
- '测试结果',
- ),
- Text(
- _result,
- style: Theme.of(context).textTheme.headlineMedium,
- ),
- ],
- ),
- ),
- // 页面底部的按钮
- bottomNavigationBar: Padding(
- padding: const EdgeInsets.all(8.0),
- child: Row(
- mainAxisAlignment: MainAxisAlignment.spaceAround, // 按钮等距排列
- children: <Widget>[
- ElevatedButton(
- onPressed: _connectTest,
- child: const Text('测试链接'),
- ),
- ElevatedButton(
- onPressed: _translationTest,
- child: const Text('测试翻译'),
- ),
- ElevatedButton(
- onPressed: _recordTest,
- child: const Text('测试录音'),
- ),
- ],
- ),
- ),
- );
- }
- }
|