Dart Audioplayers pause play audio button

import 'package:flutter/material.dart'; import 'package:audioplayers/audioplayers.dart'; void main() => runApp(MyApp()); class MyApp extends StatelessWidget { @override Widget build(BuildContext context) { return MaterialApp( debugShowCheckedModeBanner: false, title: 'Flutter Demo', home: MyHomePage(title: '2 Guys Named Chris'), ); } } class MyHomePage extends StatefulWidget { MyHomePage({Key key, this.title}) : super(key: key); final String title; @override _MyHomePageState createState() => _MyHomePageState(); } AudioPlayer audioPlayer = AudioPlayer(); class _MyHomePageState extends State<MyHomePage> { bool _isVisible = true; bool _notVisible = false; var _feedUrl = 'https://streamingfeed.com'; var _blankUrl = 'https://github.com/anars/blank-audio/raw/master/500-milliseconds-of-silence.mp3'; pausePlayToggle() { setState(() { _isVisible = !_isVisible; }); setState(() { _notVisible = !_isVisible; }); } void showPause() { pausePlayToggle(); audioPlayer.play(_feedUrl); } void showPlay() { pausePlayToggle(); audioPlayer.play(_blankUrl); } @override Widget build(BuildContext context) { return Scaffold( backgroundColor: Color(0xff000000), body: SafeArea( child: Center( child: Column( children: <Widget>[ Padding( padding: const EdgeInsets.fromLTRB(8.0, 0, 10.0, 0), child: Row( mainAxisAlignment: MainAxisAlignment.spaceBetween, children: <Widget>[ Stack( children: <Widget>[ Offstage( offstage: _isVisible, child: IconButton( icon: Icon(Icons.pause_circle_filled), iconSize: 40, color: Color(0xffcccccc), onPressed: () { showPlay(); }, ), ), Offstage( offstage: _notVisible, child: IconButton( icon: Icon(Icons.play_circle_filled), iconSize: 40, color: Color(0xffcccccc), onPressed: () { showPause(); }, ), ), //Show on Bottom //Show on Top ], ), Text( '2 GUYS NAMED CHRIS', style: TextStyle(color: Color(0xffcccccc)), ), Icon( Icons.arrow_back_ios, size: 14, color: Color(0xffcccccc), ), ], ), ), Expanded( child: Container( color: Color(0xffcccccc), ), ), ], ), ), ), ); } }
Dart file to toggle audio stream in flutter app using the audioplayers package at https://pub.dev/packages/audioplayers. I switched from using the Appbar to a container, because I have more control over the layout of the items and I can control the Appbar padding. One other point of interest to prevent skips in the streaming feed playback resuming after pause, instead of pausing the feed I play a 500 millisecond audio file that then immediately pauses. That replaces the stream and forces it to resume from the latest point.

Be the first to comment

You can use [html][/html], [css][/css], [php][/php] and more to embed the code. Urls are automatically hyperlinked. Line breaks and paragraphs are automatically generated.