일 | 월 | 화 | 수 | 목 | 금 | 토 |
---|---|---|---|---|---|---|
1 | 2 | |||||
3 | 4 | 5 | 6 | 7 | 8 | 9 |
10 | 11 | 12 | 13 | 14 | 15 | 16 |
17 | 18 | 19 | 20 | 21 | 22 | 23 |
24 | 25 | 26 | 27 | 28 | 29 | 30 |
Tags
- jetpack compose
- Freesound
- Android
- ASMR
- 파이썬
- DART
- 장자명언
- recyclerview
- Linux
- 이모지메모
- 명심보감
- FSM
- 넷플릭스
- 벤자민플랭클린
- 이모지
- Firebase
- bash
- Flutter
- 오픈소스
- Coroutine
- 공부집중
- 공자명언
- 코틀린
- kotlin
- 명언모음
- 좋은글필사하기
- 1인개발자
- Streaming
- 소울칼리버6
- androidx
Archives
- Today
- Total
Vintage appMaker의 Tech Blog
[Flutter] audioplayers를 이용한 mp3 플레이 본문
Source code or Tip/Flutter & Dart
[Flutter] audioplayers를 이용한 mp3 플레이
VintageappMaker 2022. 11. 14. 16:59
1. 설치
flutter pub add audioplayers
2. Player 객체생성 및 UI에 사용할 변수정의
3. 이벤트 핸들러 작성
initState에서
- 플레이어 상태를 채크히가 위해 onPlayerStateChanged.listen(파라메터값){}
- 플레이위치를 얻기위해 onPositionChanged.listen(파라메터값){}
를 구현한다. 파라메터값이 포함된 정보로 프로그래시브 처리와 시간을 표시할 수있다.
...
player.onPlayerStateChanged.listen((PlayerState event) {
print("state: ${event.name}");
setState(() {
if (event.name == "playing") {
isPlaying = true;
} else {
isPlaying = false;
}
});
});
player.onDurationChanged.listen((event) {
print("duration: ${event}");
});
player.onPositionChanged.listen((event) async {
var endPos = await player.getDuration();
if (endPos == null) return;
setState(() {
endPostTime = endPos.toString().split('.').first.padLeft(8, "0");
curPostTime = event.toString().split('.').first.padLeft(8, "0");
progress = event.inSeconds / endPos.inSeconds;
});
print("position: ${event.inSeconds} => ${endPos.inSeconds}");
});
...
4. 전체소스
import 'package:audioplayers/audioplayers.dart';
import 'package:flutter/material.dart';
void main() {
runApp(const MyApp());
}
class MyApp extends StatelessWidget {
const MyApp({Key? key}) : super(key: key);
// This widget is the root of your application.
@override
Widget build(BuildContext context) {
return MaterialApp(
debugShowCheckedModeBanner: false,
title: 'Audioplayers example',
theme: ThemeData(
primarySwatch: Colors.amber,
),
home: const MyHomePage(title: 'Audioplayers example'),
);
}
}
class MyHomePage extends StatefulWidget {
const MyHomePage({Key? key, required this.title}) : super(key: key);
final String title;
@override
State<MyHomePage> createState() => _MyHomePageState();
}
class _MyHomePageState extends State<MyHomePage> {
final player = AudioPlayer();
double progress = 0.0;
String curPostTime = "";
String endPostTime = "";
bool isPlaying = false;
void _incrementCounter() {
setState(() {});
}
@override
initState() {
player.onPlayerStateChanged.listen((PlayerState event) {
print("state: ${event.name}");
setState(() {
if (event.name == "playing") {
isPlaying = true;
} else {
isPlaying = false;
}
});
});
player.onDurationChanged.listen((event) {
print("duration: ${event}");
});
player.onPositionChanged.listen((event) async {
var endPos = await player.getDuration();
if (endPos == null) return;
setState(() {
endPostTime = endPos.toString().split('.').first.padLeft(8, "0");
curPostTime = event.toString().split('.').first.padLeft(8, "0");
progress = event.inSeconds / endPos.inSeconds;
});
print("position: ${event.inSeconds} => ${endPos.inSeconds}");
});
}
@override
Widget build(BuildContext context) {
return Scaffold(
body: Stack(
children: [
Image.network(
(isPlaying)
? "https://media3.giphy.com/media/5ehBR5qtLEXBe/giphy.gif?cid=ecf05e476dgsbqgg05n4mm9xgzsmppkme1lxnxxjbdevgmn7&rid=giphy.gif&ct=g"
: "https://cdn.pixabay.com/photo/2017/01/18/18/03/filter-1990470_960_720.jpg",
fit: BoxFit.cover,
width: double.infinity,
height: double.infinity),
Container(color: Colors.black.withOpacity(0.5)),
Container(
width: double.infinity,
alignment: Alignment.bottomRight,
constraints: BoxConstraints(minWidth: 300, maxWidth: 500),
child: Column(
mainAxisAlignment: MainAxisAlignment.end,
children: <Widget>[
const Text(
'Audioplayers',
style: TextStyle(fontSize: 20, color: Colors.amber),
),
SizedBox(
height: 30,
),
LinearProgressIndicator(
minHeight: 10,
value: progress,
backgroundColor: Colors.blueGrey,
valueColor: AlwaysStoppedAnimation<Color>(Colors.cyan),
),
SizedBox(
height: 5,
),
Row(
children: [
SizedBox(width: 5),
Text(
curPostTime,
style: TextStyle(color: Colors.amberAccent),
),
Spacer(),
Text(endPostTime,
style: TextStyle(color: Colors.amberAccent)),
SizedBox(width: 5)
],
)
],
),
)
],
),
floatingActionButton: FloatingActionButton(
onPressed: () {
if (isPlaying) {
player.stop();
} else {
player.play(UrlSource(
"https://cdn.freesound.org/previews/150/150537_826206-lq.mp3"));
}
},
tooltip: 'play',
child: isPlaying ? Icon(Icons.stop_circle) : Icon(Icons.play_circle),
), // This trailing comma makes auto-formatting nicer for build methods.
);
}
}
'Source code or Tip > Flutter & Dart' 카테고리의 다른 글
[Flutter] firebase cli 설정시 configure 에러 (0) | 2022.11.21 |
---|---|
[Flutter] 조건부 import (conditional import) (0) | 2022.11.19 |
[Flutter] Web App에서 javascript와 연동 (0) | 2022.11.13 |
[Flutter] Web app 배포시, 화면크기 고정 (0) | 2022.11.08 |
[Flutter] build Error 화면 커스텀하기 (0) | 2022.11.05 |
Comments