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, ), ), ), ); }, ), ), ), ); }}
评论