写点什么

Flutter & 鸿蒙 Next 实现长按录音按钮及动画特效

作者:淼.
  • 2025-03-14
    北京
  • 本文字数:3440 字

    阅读完需:约 11 分钟

在现代移动应用开发中,长按录音功能是一种常见的交互方式,尤其是在社交、语音消息和会议应用中。结合动画特效,可以显著提升用户体验。本文将详细介绍如何在 Flutter 和鸿蒙 Next 中实现长按录音按钮,并添加动画特效。



一、Flutter 实现长按录音按钮及动画特效

(一)功能需求

我们需要一个按钮,当用户长按时,开始录音并显示录音进度。长按结束时,停止录音并显示录音结果。同时,在长按时,按钮需要具备动画效果,展示录音进度或指示正在录音。

(二)实现思路

  1. 按钮 UI 设计

  2. 使用 GestureDetector 监听长按手势,设置不同的状态(长按开始、录音中、录音结束)。

  3. 动画效果

  4. 使用 AnimatedContainerAnimationController 配合 Tween 实现按钮的尺寸变化、颜色变化等动画效果。

  5. 录音功能

  6. 利用 Flutter 的录音插件 flutter_sound 来实现录音功能。

(三)代码实现

1. 添加依赖

pubspec.yaml 文件中添加所需的依赖:


dependencies:  flutter: sdk: flutter  flutter_sound: ^9.1.9  # 音频录制插件
复制代码

2. 编写 UI 和动画逻辑

import 'package:flutter/material.dart';import 'package:flutter_sound/flutter_sound.dart';
void main() => runApp(MyApp());
class MyApp extends StatelessWidget { @override Widget build(BuildContext context) { return MaterialApp( title: '长按录音按钮', theme: ThemeData(primarySwatch: Colors.blue), home: RecordingButton(), ); }}
class RecordingButton extends StatefulWidget { @override _RecordingButtonState createState() => _RecordingButtonState();}
class _RecordingButtonState extends State<RecordingButton> with TickerProviderStateMixin { FlutterSoundRecorder _recorder; // 录音器 bool _isRecording = false; // 是否正在录音 double _progress = 0.0; // 录音进度 AnimationController _animationController; // 动画控制器 Animation<double> _scaleAnimation; // 缩放动画 Animation<Color?> _colorAnimation; // 颜色变化动画
@override void initState() { super.initState(); _recorder = FlutterSoundRecorder(); _initRecorder(); _initAnimations(); }
// 初始化录音器 void _initRecorder() async { await _recorder.openAudioSession(); }
// 初始化动画控制器 void _initAnimations() { _animationController = AnimationController( vsync: this, duration: Duration(milliseconds: 200), );
_scaleAnimation = Tween<double>(begin: 1.0, end: 1.2).animate( CurvedAnimation(parent: _animationController, curve: Curves.easeInOut), );
_colorAnimation = ColorTween(begin: Colors.blue, end: Colors.red).animate( CurvedAnimation(parent: _animationController, curve: Curves.easeInOut), ); }
// 开始录音 void _startRecording() async { await _recorder.startRecorder(toFile: 'audio.aac'); setState(() { _isRecording = true; }); _animationController.forward(); _recordingProgress(); }
// 停止录音 void _stopRecording() async { await _recorder.stopRecorder(); setState(() { _isRecording = false; _progress = 0.0; }); _animationController.reverse(); }
// 录音进度 void _recordingProgress() async { while (_isRecording) { await Future.delayed(Duration(milliseconds: 100)); final progress = await _recorder.getRecordingDuration(); setState(() { _progress = progress.inSeconds.toDouble(); }); if (_progress >= 10) { // 假设录音最大为10秒 _stopRecording(); } } }
@override void dispose() { _recorder.closeAudioSession(); _animationController.dispose(); super.dispose(); }
@override Widget build(BuildContext context) { return Scaffold( appBar: AppBar(title: Text('长按录音按钮')), body: Center( child: GestureDetector( onLongPress: _startRecording, onLongPressEnd: (_) => _stopRecording(), child: AnimatedBuilder( animation: _animationController, builder: (context, child) { return Container( width: 150, height: 150, decoration: BoxDecoration( color: _colorAnimation.value, shape: BoxShape.circle, ), child: Center( child: ScaleTransition( scale: _scaleAnimation, child: Icon( _isRecording ? Icons.stop : Icons.mic, color: Colors.white, size: 80, ), ), ), ); }, ), ), ), ); }}
复制代码

(四)代码详细解释

  1. UI 和手势操作

  2. 使用 GestureDetector 监听用户的长按手势:

  3. onLongPress:当用户长按按钮时,调用 _startRecording 函数开始录音。

  4. onLongPressEnd:当长按结束时,调用 _stopRecording 停止录音。通过 AnimatedBuilder 来监听动画状态变化,更新 UI。

  5. 录音功能

  6. 使用 flutter_sound 插件来处理录音功能:

  7. _recorder.startRecorder(toFile: 'audio.aac'):开始录音并保存为 audio.aac 文件。

  8. _recorder.stopRecorder():停止录音。

  9. _recorder.getRecordingDuration():获取录音进度,通过 inSeconds 获取已录制的时间。

  10. 动画效果

  11. 使用 AnimationControllerTween 来控制动画:

  12. _scaleAnimation:通过 ScaleTransition 实现按钮的缩放。

  13. _colorAnimation:通过颜色变化动画实现按钮颜色的动态变化。



二、鸿蒙 Next 实现长按录音按钮及动画特效

鸿蒙 Next 提供了强大的动画和手势支持,可以实现类似的功能。以下是实现思路和代码示例:

(一)功能需求

  1. 长按录音:用户长按时开始录音,松开时停止录音。

  2. 动画特效:在录音过程中,按钮显示动画效果,如缩放和颜色变化。

  3. 录音进度:实时显示录音进度。

(二)实现思路

  1. 按钮 UI 设计

  2. 使用鸿蒙 Next 的 GestureDetector 监听长按手势。

  3. 动画效果

  4. 使用鸿蒙 Next 的动画 API 实现按钮的缩放和颜色变化。

  5. 录音功能

  6. 使用鸿蒙的音频录制 API 实现录音功能。

(三)代码实现

1. 添加依赖

鸿蒙 Next 的录音功能通常通过系统 API 实现,无需额外依赖。

2. 编写 UI 和动画逻辑

import { Component, State, OnAppear } from '@ohos.arkui';import { Recorder } from '@ohos.multimedia.audio';
@Componentstruct RecordingButton { @State isRecording: boolean = false; @State progress: number = 0; private recorder: Recorder;
private startRecording() { this.recorder = new Recorder(); this.recorder.start({ path: 'internal://audio/recording.aac', format: 'aac', success: () => { this.isRecording = true; this.updateProgress(); }, fail: (err) => { console.error('Recording failed:', err); } }); }
private stopRecording() { this.recorder.stop(); this.isRecording = false; this.progress = 0; }
private updateProgress() { setInterval(() => { if (this.isRecording) { this.progress += 0.1; if (this.progress >= 10) { this.stopRecording(); } } }, 100); }
build() { return ( <Column align="center" justify="center"> <Text text={this.isRecording ? 'Recording...' : 'Press to record'} /> <Button text={this.isRecording ? 'Stop' : 'Record'} onClick={this.isRecording ? this.stopRecording.bind(this) : this.startRecording.bind
复制代码


用户头像

淼.

关注

还未添加个人签名 2022-10-24 加入

还未添加个人简介

评论

发布
暂无评论
Flutter & 鸿蒙 Next 实现长按录音按钮及动画特效_淼._InfoQ写作社区