Search code examples
flutteraudiojust-audio

How to properly play audio file using just_audio - flutter


Am working on a music app were am suppose to stream audio and also play my locally stored files.

Am using flutter and am not good on it, Actually am learning.

What i wanted is to be helped on how i can play a file properly, The intention is to play a file once provided to the player path. bellow is my code.

import 'package:myApp/shared/MusicProgressIndicator.dart';
import 'package:myApp/just_audio.dart';
import 'package:myApp/app.dart';

class SingleSongScreen extends StatefulWidget {
  static const String id = "SingleSongScreen";
  static var song = {};
  SingleSongScreen({Key key}) : super(key: key);

  @override
  _SingleSongScreenState createState() => _SingleSongScreenState();
}

class _SingleSongScreenState extends State<SingleSongScreen> with TickerProviderStateMixin {
  Duration currentDuration = Duration(milliseconds: 1000);
  bool showRemaining = false;
  AnimationController controller;
  
  @override
  void initState() {
    controller = AnimationController(
      vsync: this,
      duration: const Duration(seconds: 5),
    )..addListener(() {
        setState(() {});
      });
    controller.repeat(reverse: true);
    super.initState();
  }

  @override
  void dispose() {
    controller.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    final player  = AudioPlayer();
    var song      = SingleSongScreen.song;
    var songPath  = app.base+"play.php?file="+song['song'];
    print(song);
    print(songPath);
    
    player.stop();
    player.setUrl(songPath).then((play){
       player.play();
      print("Playing now");
    });

    return Window(
      backgroundColor: backgroundColor,
      header: Container(
        child: Row(
          mainAxisAlignment: MainAxisAlignment.spaceBetween,
          children: [
            IconicButton(
              icon: backIcon,
              iconColor: Colors.grey,
              transparent: true,
              circledIcon: false,
              size: 40,
              onClicked: () {
                goBack(context);
              },
            ),
            Favicon(onClicked: () {
              goto(page: MainScreen.id, context: context);
            }),
          ],
        ),
      ),
      body: [
        VerticalSpacer(
          h: 20,
        ),
        Container(
          height: 250,
          child: Carousel(
            boxFit: BoxFit.contain,
            autoplay: carouselAutoPlay,
            animationCurve: Curves.fastOutSlowIn,
            animationDuration: Duration(milliseconds: 1000),
            dotSize: 6.0,
            dotIncreasedColor: Color(0xFF33A3FF),
            dotBgColor: Colors.transparent,
            dotPosition: DotPosition.bottomCenter,
            dotVerticalPadding: 10.0,
            showIndicator: true,
            indicatorBgPadding: 7.0,
            images: images(),
          ),
        )
      ],
      footer: Container(
        child: Column(
          children: [
            Container(
              child: Marquee(
                child: Label(
                  song['title'],
                  bold: true,
                ),
              ),
            ),
            Container(
              child: Marquee(
                child: Label(
                  song['artist'],
                  bold: true,
                  color: Colors.grey,
                ),
              ),
            ),

            // ACTION ICONS SECTION
            VerticalSpacer(
              h: 25,
            ),
            Container(
              child: Row(
                mainAxisAlignment: MainAxisAlignment.spaceBetween,
                children: [
                  VerticalIconicButton(
                    icon: FontAwesomeIcons.fileDownload,
                    label: "Download",
                    iconColor: Colors.grey,
                    textColor: Colors.grey,
                    scale: 1.2,
                    onClicked: (){
                      var downloadURL = songPath.replaceAll("play.php", "download.php");
                      app app2 = new app();
                      toast("Downloading a file "+song['song']);
                      app2.fetchServer({'method':'download','file':song['song']}).then((fileInfo){
                        if(fileInfo['status']=="success"){
                          toast("Download complete "+song['song']);
                          app2.saveDownload(song['song'],song['artist'],fileInfo['file']);
                        }else{
                          toast("There was an error while downloading a file");
                        }
                        print("downloaded file is");
                        print(fileInfo);
                      });
                    },
                  ),
                  VerticalIconicButton(
                    icon: Icons.favorite_border_outlined,
                    label: "Favourite",
                    iconColor: Colors.grey,
                    textColor: Colors.grey,
                    scale: 1.2,
                  ),
                  VerticalIconicButton(
                    icon: FontAwesomeIcons.readme,
                    label: "Lyrics",
                    iconColor: Colors.grey,
                    textColor: Colors.grey,
                    scale: 1.2,
                    onClicked: () {
                      goto(page: LyricsScreen.id, context: context, args: lyric);
                    },
                  ),
                ],
              ),
            ),

            // SONG PLAY PROGRESS INDICATOR
            VerticalSpacer(),
            MusicProgressIndicator(
              progress: currentDuration,
              buffered: Duration(milliseconds: 2000),
              total: Duration(milliseconds: 5000),
              showTotalRemainingTime: showRemaining,
              onSeek: (duration) {
                setState(() {
                  currentDuration = duration;
                  showRemaining = !showRemaining;
                });
                // _player.seek(duration);
              },
            ),

            // MUSIC PLAY CONTROLLER ACTION BUTTON

            VerticalSpacer(
              h: 20,
            ),

            Container(
              child: Row(
                mainAxisAlignment: MainAxisAlignment.spaceBetween,
                children: [
                  IconicButton(
                    icon: Icons.repeat_one,
                    iconColor: Colors.grey,
                    transparent: true,
                    circledIcon: false,
                    size: 50,
                  ),
                  Container(
                    child: Row(
                      children: [
                        Container(
                          child: Center(
                            child: IconicButton(
                              icon: Icons.skip_previous_rounded,
                              iconColor: Colors.white,
                              transparent: true,
                              circledIcon: false,
                              size: 50,
                            ),
                          ),
                        ),
                        SizedBox(width: 15),
                        IconicButton(
                          icon: Icons.pause,
                          iconColor: Colors.grey,
                          iconCircleColor: Colors.blue,
                          size: 50,
                          onClicked: (){
                            toast("Playing file");
                            player.stop();
                            player.setUrl(songPath).then((play){
                              player.play();
                              print("Playing now");
                            });
                          },
                        ),
                        SizedBox(
                          width: 15,
                        ),
                        Container(
                          child: Center(
                            child: IconicButton(
                              icon: Icons.skip_next_rounded,
                              iconColor: Colors.white,
                              transparent: true,
                              circledIcon: false,
                              size: 50,
                            ),
                          ),
                        ),
                      ],
                    ),
                  ),
                  IconicButton(
                    icon: Icons.queue_music_outlined,
                    iconColor: Colors.grey,
                    transparent: true,
                    circledIcon: false,
                    size: 50,
                    onClicked: () {
                      goto(page: AllSongsScreen.id, context: context);
                    },
                  ),
                ],
              ),
            ),

            // BOTTTOM SPACE
            VerticalSpacer(
              h: 30,
            ),
          ],
        ),
      ),
    );
  }

  void toast(String message){
    ScaffoldMessenger.of(context).showSnackBar(SnackBar(
      content:  Text(message.toString()),
      duration: const Duration(seconds: 1),
      action: SnackBarAction(
        label: 'OK',
        onPressed: () { },
      ),
    )
    );
  }
}

The code which i have used to play sound, is producing

  1. Annoying sound, something a double sounds or waves crossing
  2. It's allowing playing of multiple sounds.

Note: I purchased the template.

Thanks, Please help.


Solution

  • You have called the setState() method in the addListener of controller and directly called the player.stop() and player.play() methods inside the widget build.

    Before calling the stop or play methods, check whether the player is not null and is not playing

    if(player.playing){
    
    }
    

    And you should not initialize your player inside the widget build. It is not advisable.