当前位置:网站首页>Fluent music player audioplayer
Fluent music player audioplayer
2022-04-22 02:18:00 【weixin_ forty-four million nine hundred and eleven thousand sev】
Refer to the official website
Refer to the official website
audioplayer: ^0.8.1
import 'dart:async';
import 'dart:io';
import 'dart:typed_data';
import 'package:audioplayer/audioplayer.dart';
import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';
import 'package:http/http.dart';
import 'package:path_provider/path_provider.dart';
typedef void OnError(Exception exception);
const kUrl =
"https://www.mediacollege.com/downloads/sound-effects/nature/forest/rainforest-ambient.mp3";
void main() {
runApp(MaterialApp(home: Scaffold(body: AudioApp())));
}
enum PlayerState {
stopped, playing, paused }
class AudioApp extends StatefulWidget {
@override
_AudioAppState createState() => _AudioAppState();
}
class _AudioAppState extends State<AudioApp> {
Duration duration;
Duration position;
AudioPlayer audioPlayer;
String localFilePath;
PlayerState playerState = PlayerState.stopped;
get isPlaying => playerState == PlayerState.playing;
get isPaused => playerState == PlayerState.paused;
get durationText =>
duration != null ? duration.toString().split('.').first : '';
get positionText =>
position != null ? position.toString().split('.').first : '';
bool isMuted = false;
StreamSubscription _positionSubscription;
StreamSubscription _audioPlayerStateSubscription;
@override
void initState() {
super.initState();
initAudioPlayer();
}
@override
void dispose() {
_positionSubscription.cancel();
_audioPlayerStateSubscription.cancel();
audioPlayer.stop();
super.dispose();
}
void initAudioPlayer() {
audioPlayer = AudioPlayer();
_positionSubscription = audioPlayer.onAudioPositionChanged
.listen((p) => setState(() => position = p));
_audioPlayerStateSubscription =
audioPlayer.onPlayerStateChanged.listen((s) {
if (s == AudioPlayerState.PLAYING) {
setState(() => duration = audioPlayer.duration);
} else if (s == AudioPlayerState.STOPPED) {
onComplete();
setState(() {
position = duration;
});
}
}, onError: (msg) {
setState(() {
playerState = PlayerState.stopped;
duration = Duration(seconds: 0);
position = Duration(seconds: 0);
});
});
}
Future play() async {
await audioPlayer.play(kUrl);
setState(() {
playerState = PlayerState.playing;
});
}
Future _playLocal() async {
await audioPlayer.play(localFilePath, isLocal: true);
setState(() => playerState = PlayerState.playing);
}
Future pause() async {
await audioPlayer.pause();
setState(() => playerState = PlayerState.paused);
}
Future stop() async {
await audioPlayer.stop();
setState(() {
playerState = PlayerState.stopped;
position = Duration();
});
}
Future mute(bool muted) async {
await audioPlayer.mute(muted);
setState(() {
isMuted = muted;
});
}
void onComplete() {
setState(() => playerState = PlayerState.stopped);
}
Future<Uint8List> _loadFileBytes(String url, {
OnError onError}) async {
Uint8List bytes;
try {
bytes = await readBytes(url);
} on ClientException {
rethrow;
}
return bytes;
}
Future _loadFile() async {
final bytes = await _loadFileBytes(kUrl,
onError: (Exception exception) =>
print('_loadFile => exception $exception'));
final dir = await getApplicationDocumentsDirectory();
final file = File('${dir.path}/audio.mp3');
await file.writeAsBytes(bytes);
if (await file.exists())
setState(() {
localFilePath = file.path;
});
}
@override
Widget build(BuildContext context) {
final textTheme = Theme.of(context).textTheme;
return Center(
child: Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.spaceEvenly,
mainAxisSize: MainAxisSize.min,
children: [
Text(
'Flutter Audioplayer',
style: textTheme.headline,
),
Material(child: _buildPlayer()),
if (!kIsWeb)
localFilePath != null ? Text(localFilePath) : Container(),
if (!kIsWeb)
Padding(
padding: const EdgeInsets.all(8.0),
child: Row(
mainAxisAlignment: MainAxisAlignment.spaceEvenly,
children: [
RaisedButton(
onPressed: () => _loadFile(),
child: Text('Download'),
),
if (localFilePath != null)
RaisedButton(
onPressed: () => _playLocal(),
child: Text('play local'),
),
],
),
),
],
),
),
);
}
Widget _buildPlayer() => Container(
padding: EdgeInsets.all(16.0),
child: Column(
mainAxisSize: MainAxisSize.min,
children: [
Row(mainAxisSize: MainAxisSize.min, children: [
IconButton(
onPressed: isPlaying ? null : () => play(),
iconSize: 64.0,
icon: Icon(Icons.play_arrow),
color: Colors.cyan,
),
IconButton(
onPressed: isPlaying ? () => pause() : null,
iconSize: 64.0,
icon: Icon(Icons.pause),
color: Colors.cyan,
),
IconButton(
onPressed: isPlaying || isPaused ? () => stop() : null,
iconSize: 64.0,
icon: Icon(Icons.stop),
color: Colors.cyan,
),
]),
if (duration != null)
Slider(
value: position?.inMilliseconds?.toDouble() ?? 0.0,
onChanged: (double value) {
return audioPlayer.seek((value / 1000).roundToDouble());
},
min: 0.0,
max: duration.inMilliseconds.toDouble()),
if (position != null) _buildMuteButtons(),
if (position != null) _buildProgressView()
],
),
);
Row _buildProgressView() => Row(mainAxisSize: MainAxisSize.min, children: [
Padding(
padding: EdgeInsets.all(12.0),
child: CircularProgressIndicator(
value: position != null && position.inMilliseconds > 0
? (position?.inMilliseconds?.toDouble() ?? 0.0) /
(duration?.inMilliseconds?.toDouble() ?? 0.0)
: 0.0,
valueColor: AlwaysStoppedAnimation(Colors.cyan),
backgroundColor: Colors.grey.shade400,
),
),
Text(
position != null
? "${positionText ?? ''} / ${durationText ?? ''}"
: duration != null ? durationText : '',
style: TextStyle(fontSize: 24.0),
)
]);
Row _buildMuteButtons() {
return Row(
mainAxisAlignment: MainAxisAlignment.spaceEvenly,
children: <Widget>[
if (!isMuted)
FlatButton.icon(
onPressed: () => mute(true),
icon: Icon(
Icons.headset_off,
color: Colors.cyan,
),
label: Text('Mute', style: TextStyle(color: Colors.cyan)),
),
if (isMuted)
FlatButton.icon(
onPressed: () => mute(false),
icon: Icon(Icons.headset, color: Colors.cyan),
label: Text('Unmute', style: TextStyle(color: Colors.cyan)),
),
],
);
}
}
版权声明
本文为[weixin_ forty-four million nine hundred and eleven thousand sev]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/04/202204220213163707.html
边栏推荐
- 72 page Internet smart Park solution
- SV知识点回顾
- What about first-class insurance? Is there a charge? What are the waiting requirements?
- Mysql-if-then-else statement
- 我靠,有人在我的代码注释里的“下毒”?
- 头歌 NAT&DHCP协议分析
- Why is Nacos so strong
- 【查看已经安装的包和命令是由哪个包提供的】
- Introduction to Alibaba's super large-scale Flink cluster operation and maintenance system
- DEJA_VU3D - Cesium功能集 之 013-军事标绘系列七:正多边形
猜你喜欢

Shit, someone poisoned my code comments?

Unity Game Optimization - Third Edition 阅读笔记 Chapter 1 分析性能问题

Leetcode-232 - queue implementation with stack

Redis cache database uses redis shake for data synchronization

Advanced formula 43 of C language: the meaning of function

Jetcode prize essay solicitation activity | interesting stories of low code industry waiting for you to share

72 page Internet smart Park solution

Uniapp realizes the effect of birth date / time selection

信息安全概述

NLP model summary
随机推荐
uniapp处理强制刷新问题
Xu Yuandong was invited to share "Ltd digital business methodology" at Shanghai Management Technology Forum
DEJA_VU3D - Cesium功能集 之 012-军事标绘系列六:自定义多边形
[programming question] interesting numbers
(counting line segment tree) lintcode medium 248 · count the number of numbers smaller than a given integer
Advanced formula 44 of C language: the secret of function parameters (Part 1)
Analysis and interpretation of the current situation and challenges faced by enterprise operation and maintenance in the digital era
JMeter+Jenkins+Ant持续化
[check which package provides the installed packages and commands]
Golang 中 select 语句死锁问题
Use of greendao;
uniapp实现出生日期/时间选择效果
Register login 1
Target motion model - uniform motion CV
13. Installation mode of system software
MySQL restores data through binlog
3D album template (size can be changed)
Unity game optimization - third edition reading notes Chapter 1 analyze performance problems
Mysql database fields move up and down
Swoole high performance in memory database use and configuration tutorial