Flutter音频录制插件fancy_audio_recorder的使用

Flutter音频录制插件fancy_audio_recorder的使用

fancy_audio_recorder 是一个简单易用的音频录制插件(就像即食汤一样)。

示例

开始使用

TODO: 列出前提条件并提供或指向如何开始使用该包的信息。

使用方法

要查看完整的示例代码,请前往 /example 文件夹。

AudioRecorderButton(
    maxRecordTime: const Duration(seconds: 80), // 设置最大录音时间为80秒
    onRecordComplete: (value) { // 录音完成时的回调函数
        log('$value'); // 打印录音文件路径
    },
),

完整示例代码

import 'dart:log'; // 导入日志库

import 'package:fancy_audio_recorder/fancy_audio_recorder.dart'; // 导入音频录制插件
import 'package:flutter/material.dart'; // 导入Flutter框架

void main() {
  runApp(const MyApp()); // 运行应用
}

class MyApp extends StatelessWidget {
  const MyApp({super.key}); // 构造函数

  [@override](/user/override)
  Widget build(BuildContext context) {
    return MaterialApp( // 创建MaterialApp实例
      title: 'Fancy Sample App', // 应用标题
      theme: ThemeData( // 主题设置
        colorScheme: ColorScheme.fromSeed(seedColor: Colors.deepPurple),
        useMaterial3: true,
      ),
      home: const MyHomePage(title: 'Fancy Sample App'), // 主页
    );
  }
}

class MyHomePage extends StatefulWidget {
  const MyHomePage({super.key, required this.title}); // 构造函数

  final String title; // 标题

  [@override](/user/override)
  State<MyHomePage> createState() => _MyHomePageState(); // 创建状态类
}

class _MyHomePageState extends State<MyHomePage> {
  String? audioPath; // 存储录音文件路径

  [@override](/user/override)
  Widget build(BuildContext context) {
    return Scaffold(
        appBar: AppBar( // 创建AppBar
          backgroundColor: Theme.of(context).colorScheme.inversePrimary, // 设置背景颜色
          title: Text(widget.title), // 设置标题
        ),
        body: Center( // 设置中心对齐
          child: Column(
            mainAxisSize: MainAxisSize.min, // 设置最小高度
            children: [
              AudioRecorderButton( // 创建录音按钮
                maxRecordTime: const Duration(seconds: 80), // 设置最大录音时间
                onRecordComplete: (audioPath) { // 录音完成时的回调函数
                  log('$audioPath'); // 打印录音文件路径
                  setState(() { // 更新UI
                    this.audioPath = audioPath;
                  });
                },
              ),
              Text('$audioPath'), // 显示录音文件路径
            ],
          ),
        ));
  }
}

更多关于Flutter音频录制插件fancy_audio_recorder的使用的实战教程也可以访问 https://www.itying.com/category-92-b0.html

1 回复

更多关于Flutter音频录制插件fancy_audio_recorder的使用的实战系列教程也可以访问 https://www.itying.com/category-92-b0.html


当然,下面是一个关于如何使用Flutter音频录制插件fancy_audio_recorder的示例代码。这个示例将展示如何初始化fancy_audio_recorder插件,开始和停止录音,以及保存录音文件。

首先,确保你已经在pubspec.yaml文件中添加了fancy_audio_recorder依赖:

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

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

接下来是主代码部分,这里展示了一个简单的Flutter应用,包含开始录音和停止录音的按钮,并将录音文件保存到设备中。

import 'package:flutter/material.dart';
import 'package:fancy_audio_recorder/fancy_audio_recorder.dart';
import 'dart:io';

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

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Audio Recorder Demo',
      theme: ThemeData(
        primarySwatch: Colors.blue,
      ),
      home: AudioRecorderScreen(),
    );
  }
}

class AudioRecorderScreen extends StatefulWidget {
  @override
  _AudioRecorderScreenState createState() => _AudioRecorderScreenState();
}

class _AudioRecorderScreenState extends State<AudioRecorderScreen> {
  FancyAudioRecorder? _audioRecorder;
  String _status = "Ready to Record";
  File? _recordedFile;

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

  Future<void> _initAudioRecorder() async {
    _audioRecorder = FancyAudioRecorder(
      audioFormat: AudioFormat.mp3, // 或者使用 AudioFormat.wav
      codec: AudioCodec.aac, // 对于mp3格式,codec参数将被忽略
      sampleRate: 44100,
      numChannels: 2,
      bitRate: 128000,
    );

    // 监听录音状态变化
    _audioRecorder!.onStatusChanged!.listen((status) {
      setState(() {
        _status = status;
      });
    });

    // 监听录音路径变化(文件保存路径)
    _audioRecorder!.onPathChanged!.listen((path) {
      setState(() {
        _recordedFile = File(path);
      });
    });
  }

  @override
  void dispose() {
    _audioRecorder?.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('Audio Recorder Demo'),
      ),
      body: Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: <Widget>[
            Text(
              _status,
              style: TextStyle(fontSize: 20),
            ),
            SizedBox(height: 20),
            ElevatedButton(
              onPressed: () async {
                if (_audioRecorder!.isRecording) {
                  await _audioRecorder!.stop();
                } else {
                  await _audioRecorder!.start(path: 'path_to_save_audio_file.mp3');
                }
              },
              child: Text(_audioRecorder!.isRecording ? 'Stop Recording' : 'Start Recording'),
            ),
            if (_recordedFile != null)
              SizedBox(height: 20),
              ElevatedButton(
                onPressed: () {
                  // 这里可以添加分享或播放录音文件的逻辑
                  // 例如,使用 url_launcher 打开文件
                  // _launchURL('file://${_recordedFile!.path}');
                  print('Recorded file path: ${_recordedFile!.path}');
                },
                child: Text('View Recorded File'),
              ),
          ],
        ),
      ),
    );
  }

  // 示例:使用 url_launcher 打开文件(需要额外添加依赖)
  // _launchURL(String url) async {
  //   if (await canLaunch(url)) {
  //     await launch(url);
  //   } else {
  //     throw 'Could not launch $url';
  //   }
  // }
}

注意事项:

  1. 权限:在Android上,你需要请求存储权限来保存录音文件。你可以在AndroidManifest.xml中添加权限请求,并在运行时请求权限(使用permission_handler插件)。
  2. 文件路径:在iOS上,由于沙盒机制,你需要将文件保存在应用的文档目录中,并通过file://URL访问它。
  3. 依赖:如果你需要打开或分享录音文件,可能需要额外的依赖,比如url_launcher

这个示例代码展示了如何使用fancy_audio_recorder进行基本的音频录制功能。你可以根据需要进一步扩展和自定义。

回到顶部