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.
    );
  }
}
Comments