Flutter获取音频路径后如何实现音频播放?
基于路径实现音频播放的方案
1. 添加音频播放依赖
使用audioplayers库实现播放功能,先在pubspec.yaml中添加依赖:
dependencies: audioplayers: ^4.0.1 # 建议使用最新版本
执行命令安装依赖:
flutter pub get
2. 初始化音频播放器
在页面的State类中定义播放器实例,并完成初始化与资源释放:
import 'package:audioplayers/audioplayers.dart'; // 你的State类内部 late AudioPlayer _audioPlayer; String? _currentPlayingPath; // 记录当前播放的音频路径 @override void initState() { super.initState(); _audioPlayer = AudioPlayer(); // 监听播放完成事件,重置播放状态 _audioPlayer.onPlayerStateChanged.listen((state) { if (state == PlayerState.completed) { setState(() => _currentPlayingPath = null); } }); } @override void dispose() { _audioPlayer.dispose(); // 释放播放器资源 super.dispose(); }
3. 修改ListView的ListTile,添加播放控制
改造原有ListTile,加入播放/暂停按钮,实现点击播放对应路径的音频:
ListTile( title: Text(files[index].path.split('/').last), trailing: Row( mainAxisSize: MainAxisSize.min, children: [ FutureBuilder<int>( builder: (context, snapshot) { return Text(snapshot.data?.toString() ?? '0'); }, future: files[index].length(), ), const SizedBox(width: 8), IconButton( icon: Icon( _currentPlayingPath == files[index].path ? Icons.pause : Icons.play_arrow, ), onPressed: () async { if (_currentPlayingPath == files[index].path) { // 当前音频正在播放,执行暂停 await _audioPlayer.pause(); setState(() => _currentPlayingPath = null); } else { // 停止之前的播放(如果有) if (_currentPlayingPath != null) { await _audioPlayer.stop(); } // 播放当前选中的音频 await _audioPlayer.play(DeviceFileSource(files[index].path)); setState(() => _currentPlayingPath = files[index].path); } }, ), ], ), )
4. 权限配置
- Android:在
android/app/src/main/AndroidManifest.xml中添加存储读取权限:
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/>
- iOS:在
ios/Runner/Info.plist中添加访问音频的权限说明:
<key>NSAppleMusicUsageDescription</key> <string>需要访问设备中的音频文件以进行播放</string>
内容的提问来源于stack exchange,提问作者Faizan Abbas Bangash
相关产品推荐
相关产品推荐

