Flutter隐私保护插件whisper_flutter的使用

发布于 1周前 作者 eggper 来自 Flutter

Flutter隐私保护插件whisper_flutter的使用

安装库

首先,您需要在Flutter项目中添加whisper_flutter插件。可以通过以下命令安装:

flutter pub add whisper_flutter

导入库

在您的Dart文件中导入whisper_flutter库:

import 'package:whisper_flutter/whisper_flutter.dart';

编译 whisper.cpp 到共享库

无需手动编译 whisper.cpp,因为该过程会在您构建Flutter应用程序时自动完成。

快速开始

以下是快速启动示例代码,演示如何使用whisper_flutter进行语音转文字操作:

Whisper whisper = Whisper();
var res = await whisper.request(
    whisperLib: "libwhisper.so",
    whisperRequest: WhisperRequest.fromWavFile(
        audio: File(audio),
        model: File(model),
    ),
);

示例Demo

以下是一个完整的示例demo,展示了如何在Flutter应用中集成和使用whisper_flutter插件来实现语音转文字功能。

main.dart

// ignore_for_file: non_constant_identifier_names, unnecessary_brace_in_string_interps, depend_on_referenced_packages

import 'dart:io';
import 'package:file_picker/file_picker.dart';
import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';
import 'package:whisper_flutter/whisper_flutter.dart';
import 'package:cool_alert/cool_alert.dart';

void main() {
  WidgetsFlutterBinding.ensureInitialized();
  runApp(
    MaterialApp(
      title: 'Flutter Demo',
      theme: ThemeData(
        primarySwatch: Colors.blue,
      ),
      home: const MyHomePage(title: 'Flutter Demo Whisper Speech to Text'),
    ),
  );
}

class MyHomePage extends StatefulWidget {
  final String title;
  const MyHomePage({
    super.key,
    required this.title,
  });

  @override
  State<MyHomePage> createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {
  String model = "";
  String audio = "";
  String result = "";
  bool is_procces = false;

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text(widget.title),
      ),
      body: SingleChildScrollView(
        child: ConstrainedBox(
          constraints: BoxConstraints(
            minHeight: MediaQuery.of(context).size.height,
            minWidth: MediaQuery.of(context).size.width,
          ),
          child: Column(
            mainAxisAlignment: MainAxisAlignment.center,
            children: [
              Visibility(
                visible: !is_procces,
                child: Row(
                  mainAxisAlignment: MainAxisAlignment.center,
                  crossAxisAlignment: CrossAxisAlignment.center,
                  children: [
                    Padding(
                      padding: const EdgeInsets.all(10),
                      child: ElevatedButton(
                        onPressed: () async {
                          FilePickerResult? resul =
                              await FilePicker.platform.pickFiles();
                          if (resul != null) {
                            File file = File(resul.files.single.path!);
                            if (file.existsSync()) {
                              setState(() {
                                model = file.path;
                              });
                            }
                          }
                        },
                        child: const Text("Set Model"),
                      ),
                    ),
                    Padding(
                      padding: const EdgeInsets.all(10),
                      child: ElevatedButton(
                        onPressed: () async {
                          FilePickerResult? resul =
                              await FilePicker.platform.pickFiles();

                          if (resul != null) {
                            File file = File(resul.files.single.path!);
                            if (file.existsSync()) {
                              setState(() {
                                audio = file.path;
                              });
                            }
                          }
                        },
                        child: const Text("Set Audio"),
                      ),
                    ),
                    Padding(
                      padding: const EdgeInsets.all(10),
                      child: ElevatedButton(
                        onPressed: () async {
                          if (is_procces) {
                            return await CoolAlert.show(
                              context: context,
                              type: CoolAlertType.info,
                              text:
                                  "Please wait until the previous process finishes.",
                            );
                          }
                          if (audio.isEmpty) {
                            await CoolAlert.show(
                              context: context,
                              type: CoolAlertType.info,
                              text:
                                  "Audio is empty. Please set it first.",
                            );
                            if (kDebugMode) {
                              print("audio is empty");
                            }
                            return;
                          }
                          if (model.isEmpty) {
                            await CoolAlert.show(
                                context: context,
                                type: CoolAlertType.info,
                                text:
                                    "Model is empty. Please set it first.");
                            if (kDebugMode) {
                              print("model is empty");
                            }
                            return;
                          }

                          Future(() async {
                            print("Started transcribe");

                            Whisper whisper = Whisper(
                              whisperLib: "libwhisper.so",
                            );
                            var res = await whisper.request(
                              whisperRequest: WhisperRequest.fromWavFile(
                                audio: File(audio),
                                model: File(model),
                              ),
                            );
                            setState(() {
                              result = res.toString();
                              is_procces = false;
                            });
                          });
                          setState(() {
                            is_procces = true;
                          });
                        },
                        child: const Text("Start"),
                      ),
                    ),
                  ],
                ),
                replacement: const CircularProgressIndicator(),
              ),
              Padding(
                padding: const EdgeInsets.all(10),
                child: Text("Model: ${model}"),
              ),
              Padding(
                padding: const EdgeInsets.all(10),
                child: Text("Audio: ${audio}"),
              ),
              Padding(
                padding: const EdgeInsets.all(10),
                child: Text("Result: ${result}"),
              ),
            ],
          ),
        ),
      ),
    );
  }
}

此示例包含了一个简单的UI界面,允许用户选择音频文件和模型文件,并通过点击“Start”按钮将音频文件转换为文本。结果会显示在界面上。


更多关于Flutter隐私保护插件whisper_flutter的使用的实战系列教程也可以访问 https://www.itying.com/category-92-b0.html

1 回复

更多关于Flutter隐私保护插件whisper_flutter的使用的实战系列教程也可以访问 https://www.itying.com/category-92-b0.html


当然,以下是如何在Flutter项目中使用whisper_flutter插件来保护用户隐私的示例代码。whisper_flutter插件通常用于在应用中处理敏感信息,比如用户输入时隐藏或模糊化敏感数据。需要注意的是,具体的插件功能和使用方法可能会根据插件版本和Flutter SDK版本有所不同,因此请参考插件的官方文档进行确认。

1. 添加依赖

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

dependencies:
  flutter:
    sdk: flutter
  whisper_flutter: ^最新版本号  # 请替换为最新版本号

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

2. 导入插件

在你需要使用隐私保护功能的Dart文件中导入插件:

import 'package:whisper_flutter/whisper_flutter.dart';

3. 使用Whisper进行隐私保护

假设你有一个TextField,你希望用户输入敏感信息时能够隐藏或模糊化这些输入。以下是如何使用whisper_flutter来实现这一点的示例代码:

import 'package:flutter/material.dart';
import 'package:whisper_flutter/whisper_flutter.dart';

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

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Whisper Example',
      theme: ThemeData(
        primarySwatch: Colors.blue,
      ),
      home: Scaffold(
        appBar: AppBar(
          title: Text('Flutter Whisper Example'),
        ),
        body: Center(
          child: WhisperTextFieldExample(),
        ),
      ),
    );
  }
}

class WhisperTextFieldExample extends StatefulWidget {
  @override
  _WhisperTextFieldExampleState createState() => _WhisperTextFieldExampleState();
}

class _WhisperTextFieldExampleState extends State<WhisperTextFieldExample> {
  final WhisperController _whisperController = WhisperController();
  TextEditingController _textEditingController = TextEditingController();

  @override
  void dispose() {
    _whisperController.dispose();
    _textEditingController.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return Column(
      mainAxisAlignment: MainAxisAlignment.center,
      children: <Widget>[
        WhisperTextField(
          controller: _textEditingController,
          whisperController: _whisperController,
          decoration: InputDecoration(
            labelText: 'Enter Sensitive Information',
          ),
          onWhisperStatusChanged: (status) {
            // Handle whisper status change if needed
            print('Whisper status changed: $status');
          },
        ),
        SizedBox(height: 20),
        ElevatedButton(
          onPressed: () {
            // Get the text from the WhisperTextField
            String sensitiveText = _textEditingController.text;
            // Handle the sensitive text securely
            print('Sensitive text: $sensitiveText');
          },
          child: Text('Submit'),
        ),
      ],
    );
  }
}

注意事项

  1. WhisperControllerWhisperController用于控制WhisperTextField的隐私保护状态,比如开启或关闭模糊化。
  2. onWhisperStatusChanged:这是一个回调函数,当WhisperTextField的隐私保护状态改变时会被调用。
  3. 安全处理:在实际应用中,获取到的敏感信息应该进行安全处理,比如加密存储或传输。

请确保你已经正确安装并配置了whisper_flutter插件,并根据你的实际需求调整上述代码。如果你需要更高级的功能,比如自定义模糊效果或动态隐私控制,请参考插件的官方文档。

回到顶部