flutter中使用基于flutter_sound的flutter_sound_record录音

2024-01-21 12:12

本文主要是介绍flutter中使用基于flutter_sound的flutter_sound_record录音,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!

flutter_sound_record

    • 前言
    • 文章案例所使用插件的版本号
    • 插件安装
    • 引入安卓和ios权限
    • 支持的编码
    • 自定义生成的文件名
    • 代码
        • main.dart
        • audio_player.dart
    • 源码地址

前言

使用flutter_sound,总是出现莫名的错误,所以改为flutter_sound_record,实现录音录制和播放

文章案例所使用插件的版本号

3.3.2

插件安装

安装方式:
命令行形式:

flutter pub add flutter_sound_record

pubspec.yaml格式 (别忘运行 pub get):

dependencies:flutter_sound_record: ^3.3.2

引入

import 'package:flutter_sound_record/flutter_sound_record.dart';

引入安卓和ios权限

Android

<uses-permission android:name="android.permission.RECORD_AUDIO" />
<!-- Optional, you'll have to check this permission by yourself. -->
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />

min SDK: 16 (29 if you use OPUS)

iOs

<key>NSMicrophoneUsageDescription</key>
<string>We need to access to the microphone to record audio file</string>

min SDK: 8.0 (11 if you use OPUS)

支持的编码

enum AudioEncoder {/// Will output to MPEG_4 format containerAAC,/// Will output to MPEG_4 format containerAAC_LD,/// Will output to MPEG_4 format containerAAC_HE,/// sampling rate should be set to 8kHz/// Will output to 3GP format container on AndroidAMR_NB,/// sampling rate should be set to 16kHz/// Will output to 3GP format container on AndroidAMR_WB,/// Will output to MPEG_4 format container/// /!\ SDK 29 on Android /!\/// /!\ SDK 11 on iOs /!\OPUS,
}

自定义生成的文件名

在下面main.dart的代码中的 _start() 函数

await _audioRecorder.start();
//path改为自定义的即可,其余参数根据自己需求设置
await _audioRecorder.start(path: 'aFullPath/myFile.m4a', // requiredencoder: AudioEncoder.AAC, // by defaultbitRate: 128000, // by defaultsampleRate: 44100, // by default
);

代码

main.dart
import 'dart:async';import 'package:example/audio_player.dart';
import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';
import 'package:flutter_sound_record/flutter_sound_record.dart';
import 'package:just_audio/just_audio.dart' as ap;class AudioRecorder extends StatefulWidget {const AudioRecorder({required this.onStop, Key? key}) : super(key: key);final void Function(String path) onStop;@override_AudioRecorderState createState() => _AudioRecorderState();@overridevoid debugFillProperties(DiagnosticPropertiesBuilder properties) {super.debugFillProperties(properties);properties.add(ObjectFlagProperty<void Function(String path)>.has('onStop', onStop));}
}class _AudioRecorderState extends State<AudioRecorder> {bool _isRecording = false;bool _isPaused = false;int _recordDuration = 0;Timer? _timer;Timer? _ampTimer;final FlutterSoundRecord _audioRecorder = FlutterSoundRecord();Amplitude? _amplitude;@overridevoid initState() {_isRecording = false;super.initState();}@overridevoid dispose() {_timer?.cancel();_ampTimer?.cancel();_audioRecorder.dispose();super.dispose();}@overrideWidget build(BuildContext context) {return MaterialApp(home: Scaffold(body: Column(mainAxisAlignment: MainAxisAlignment.center,children: <Widget>[Row(mainAxisAlignment: MainAxisAlignment.center,children: <Widget>[_buildRecordStopControl(),const SizedBox(width: 20),_buildPauseResumeControl(),const SizedBox(width: 20),_buildText(),],),if (_amplitude != null) ...<Widget>[const SizedBox(height: 40),Text('Current: ${_amplitude?.current ?? 0.0}'),Text('Max: ${_amplitude?.max ?? 0.0}'),],],),),);}Widget _buildRecordStopControl() {late Icon icon;late Color color;if (_isRecording || _isPaused) {icon = const Icon(Icons.stop, color: Colors.red, size: 30);color = Colors.red.withOpacity(0.1);} else {final ThemeData theme = Theme.of(context);icon = Icon(Icons.mic, color: theme.primaryColor, size: 30);color = theme.primaryColor.withOpacity(0.1);}return ClipOval(child: Material(color: color,child: InkWell(child: SizedBox(width: 56, height: 56, child: icon),onTap: () {_isRecording ? _stop() : _start();},),),);}Widget _buildPauseResumeControl() {if (!_isRecording && !_isPaused) {return const SizedBox.shrink();}late Icon icon;late Color color;if (!_isPaused) {icon = const Icon(Icons.pause, color: Colors.red, size: 30);color = Colors.red.withOpacity(0.1);} else {final ThemeData theme = Theme.of(context);icon = const Icon(Icons.play_arrow, color: Colors.red, size: 30);color = theme.primaryColor.withOpacity(0.1);}return ClipOval(child: Material(color: color,child: InkWell(child: SizedBox(width: 56, height: 56, child: icon),onTap: () {_isPaused ? _resume() : _pause();},),),);}Widget _buildText() {if (_isRecording || _isPaused) {return _buildTimer();}return const Text('Waiting to record');}Widget _buildTimer() {final String minutes = _formatNumber(_recordDuration ~/ 60);final String seconds = _formatNumber(_recordDuration % 60);return Text('$minutes : $seconds',style: const TextStyle(color: Colors.red),);}String _formatNumber(int number) {String numberStr = number.toString();if (number < 10) {numberStr = '0$numberStr';}return numberStr;}Future<void> _start() async {try {if (await _audioRecorder.hasPermission()) {await _audioRecorder.start();bool isRecording = await _audioRecorder.isRecording();setState(() {_isRecording = isRecording;_recordDuration = 0;});_startTimer();}} catch (e) {if (kDebugMode) {print(e);}}}Future<void> _stop() async {_timer?.cancel();_ampTimer?.cancel();final String? path = await _audioRecorder.stop();widget.onStop(path!);setState(() => _isRecording = false);}Future<void> _pause() async {_timer?.cancel();_ampTimer?.cancel();await _audioRecorder.pause();setState(() => _isPaused = true);}Future<void> _resume() async {_startTimer();await _audioRecorder.resume();setState(() => _isPaused = false);}void _startTimer() {_timer?.cancel();_ampTimer?.cancel();_timer = Timer.periodic(const Duration(seconds: 1), (Timer t) {setState(() => _recordDuration++);});_ampTimer = Timer.periodic(const Duration(milliseconds: 200), (Timer t) async {_amplitude = await _audioRecorder.getAmplitude();setState(() {});});}
}void main() {runApp(const MyApp());
}class MyApp extends StatefulWidget {const MyApp({Key? key}) : super(key: key);@override_MyAppState createState() => _MyAppState();
}class _MyAppState extends State<MyApp> {bool showPlayer = false;ap.AudioSource? audioSource;@overridevoid initState() {showPlayer = false;super.initState();}@overrideWidget build(BuildContext context) {return MaterialApp(home: Scaffold(body: Center(child: showPlayer? Padding(padding: const EdgeInsets.symmetric(horizontal: 25),child: AudioPlayer(source: audioSource!,onDelete: () {setState(() => showPlayer = false);},),): AudioRecorder(onStop: (String path) {setState(() {audioSource = ap.AudioSource.uri(Uri.parse(path));showPlayer = true;});},),),),);}@overridevoid debugFillProperties(DiagnosticPropertiesBuilder properties) {super.debugFillProperties(properties);properties.add(DiagnosticsProperty<bool>('showPlayer', showPlayer));properties.add(DiagnosticsProperty<ap.AudioSource?>('audioSource', audioSource));}
}
audio_player.dart
import 'dart:async';import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';
import 'package:just_audio/just_audio.dart' as ap;class AudioPlayer extends StatefulWidget {const AudioPlayer({required this.source,required this.onDelete,Key? key,}) : super(key: key);/// Path from where to play recorded audiofinal ap.AudioSource source;/// Callback when audio file should be removed/// Setting this to null hides the delete buttonfinal VoidCallback onDelete;@overrideAudioPlayerState createState() => AudioPlayerState();@overridevoid debugFillProperties(DiagnosticPropertiesBuilder properties) {super.debugFillProperties(properties);properties.add(DiagnosticsProperty<ap.AudioSource>('source', source));properties.add(ObjectFlagProperty<VoidCallback>.has('onDelete', onDelete));}
}class AudioPlayerState extends State<AudioPlayer> {static const double _controlSize = 56;static const double _deleteBtnSize = 24;final ap.AudioPlayer _audioPlayer = ap.AudioPlayer();late StreamSubscription<ap.PlayerState> _playerStateChangedSubscription;late StreamSubscription<Duration?> _durationChangedSubscription;late StreamSubscription<Duration> _positionChangedSubscription;@overridevoid initState() {_playerStateChangedSubscription = _audioPlayer.playerStateStream.listen((ap.PlayerState state) async {if (state.processingState == ap.ProcessingState.completed) {await stop();}setState(() {});});_positionChangedSubscription = _audioPlayer.positionStream.listen((Duration position) => setState(() {}));_durationChangedSubscription = _audioPlayer.durationStream.listen((Duration? duration) => setState(() {}));_init();super.initState();}Future<void> _init() async {await _audioPlayer.setAudioSource(widget.source);}@overridevoid dispose() {_playerStateChangedSubscription.cancel();_positionChangedSubscription.cancel();_durationChangedSubscription.cancel();_audioPlayer.dispose();super.dispose();}@overrideWidget build(BuildContext context) {return LayoutBuilder(builder: (BuildContext context, BoxConstraints constraints) {return Row(mainAxisAlignment: MainAxisAlignment.spaceBetween,children: <Widget>[_buildControl(),_buildSlider(constraints.maxWidth),IconButton(icon: const Icon(Icons.delete,color: Color(0xFF73748D),size: _deleteBtnSize,),onPressed: () {// ignore: always_specify_types_audioPlayer.stop().then((value) => widget.onDelete());},),],);},);}Widget _buildControl() {Icon icon;Color color;if (_audioPlayer.playerState.playing) {icon = const Icon(Icons.pause, color: Colors.red, size: 30);color = Colors.red.withOpacity(0.1);} else {final ThemeData theme = Theme.of(context);icon = Icon(Icons.play_arrow, color: theme.primaryColor, size: 30);color = theme.primaryColor.withOpacity(0.1);}return ClipOval(child: Material(color: color,child: InkWell(child: SizedBox(width: _controlSize, height: _controlSize, child: icon),onTap: () {if (_audioPlayer.playerState.playing) {pause();} else {play();}},),),);}Widget _buildSlider(double widgetWidth) {final Duration position = _audioPlayer.position;final Duration? duration = _audioPlayer.duration;bool canSetValue = false;if (duration != null) {canSetValue = position.inMilliseconds > 0;canSetValue &= position.inMilliseconds < duration.inMilliseconds;}double width = widgetWidth - _controlSize - _deleteBtnSize;width -= _deleteBtnSize;return SizedBox(width: width,child: Slider(activeColor: Theme.of(context).primaryColor,inactiveColor: Theme.of(context).colorScheme.secondary,onChanged: (double v) {if (duration != null) {final double position = v * duration.inMilliseconds;_audioPlayer.seek(Duration(milliseconds: position.round()));}},value: canSetValue && duration != null ? position.inMilliseconds / duration.inMilliseconds : 0.0,),);}Future<void> play() {return _audioPlayer.play();}Future<void> pause() {return _audioPlayer.pause();}Future<void> stop() async {await _audioPlayer.stop();return _audioPlayer.seek(Duration.zero);}
}

源码地址

https://github.com/josephcrowell/flutter_sound_record/

这篇关于flutter中使用基于flutter_sound的flutter_sound_record录音的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!



http://www.chinasem.cn/article/629499

相关文章

如何使用celery进行异步处理和定时任务(django)

《如何使用celery进行异步处理和定时任务(django)》文章介绍了Celery的基本概念、安装方法、如何使用Celery进行异步任务处理以及如何设置定时任务,通过Celery,可以在Web应用中... 目录一、celery的作用二、安装celery三、使用celery 异步执行任务四、使用celery

使用Python绘制蛇年春节祝福艺术图

《使用Python绘制蛇年春节祝福艺术图》:本文主要介绍如何使用Python的Matplotlib库绘制一幅富有创意的“蛇年有福”艺术图,这幅图结合了数字,蛇形,花朵等装饰,需要的可以参考下... 目录1. 绘图的基本概念2. 准备工作3. 实现代码解析3.1 设置绘图画布3.2 绘制数字“2025”3.3

Jsoncpp的安装与使用方式

《Jsoncpp的安装与使用方式》JsonCpp是一个用于解析和生成JSON数据的C++库,它支持解析JSON文件或字符串到C++对象,以及将C++对象序列化回JSON格式,安装JsonCpp可以通过... 目录安装jsoncppJsoncpp的使用Value类构造函数检测保存的数据类型提取数据对json数

python使用watchdog实现文件资源监控

《python使用watchdog实现文件资源监控》watchdog支持跨平台文件资源监控,可以检测指定文件夹下文件及文件夹变动,下面我们来看看Python如何使用watchdog实现文件资源监控吧... python文件监控库watchdogs简介随着Python在各种应用领域中的广泛使用,其生态环境也

Python中构建终端应用界面利器Blessed模块的使用

《Python中构建终端应用界面利器Blessed模块的使用》Blessed库作为一个轻量级且功能强大的解决方案,开始在开发者中赢得口碑,今天,我们就一起来探索一下它是如何让终端UI开发变得轻松而高... 目录一、安装与配置:简单、快速、无障碍二、基本功能:从彩色文本到动态交互1. 显示基本内容2. 创建链

springboot整合 xxl-job及使用步骤

《springboot整合xxl-job及使用步骤》XXL-JOB是一个分布式任务调度平台,用于解决分布式系统中的任务调度和管理问题,文章详细介绍了XXL-JOB的架构,包括调度中心、执行器和Web... 目录一、xxl-job是什么二、使用步骤1. 下载并运行管理端代码2. 访问管理页面,确认是否启动成功

使用Nginx来共享文件的详细教程

《使用Nginx来共享文件的详细教程》有时我们想共享电脑上的某些文件,一个比较方便的做法是,开一个HTTP服务,指向文件所在的目录,这次我们用nginx来实现这个需求,本文将通过代码示例一步步教你使用... 在本教程中,我们将向您展示如何使用开源 Web 服务器 Nginx 设置文件共享服务器步骤 0 —

Java中switch-case结构的使用方法举例详解

《Java中switch-case结构的使用方法举例详解》:本文主要介绍Java中switch-case结构使用的相关资料,switch-case结构是Java中处理多个分支条件的一种有效方式,它... 目录前言一、switch-case结构的基本语法二、使用示例三、注意事项四、总结前言对于Java初学者

Golang使用minio替代文件系统的实战教程

《Golang使用minio替代文件系统的实战教程》本文讨论项目开发中直接文件系统的限制或不足,接着介绍Minio对象存储的优势,同时给出Golang的实际示例代码,包括初始化客户端、读取minio对... 目录文件系统 vs Minio文件系统不足:对象存储:miniogolang连接Minio配置Min

使用Python绘制可爱的招财猫

《使用Python绘制可爱的招财猫》招财猫,也被称为“幸运猫”,是一种象征财富和好运的吉祥物,经常出现在亚洲文化的商店、餐厅和家庭中,今天,我将带你用Python和matplotlib库从零开始绘制一... 目录1. 为什么选择用 python 绘制?2. 绘图的基本概念3. 实现代码解析3.1 设置绘图画