Basic Music Player Functionality in Flutter App
Hello folks, when you are building your app, you probably need to play a sound in the background, let’s assume that you are building a game and you need to play a sound continuously in a loop.
In this story, we are going to play a sound with a basic button. To do this we are going to use a package named “AudioPlayers”.
audioplayers | Flutter Package
A Flutter plugin to play multiple simultaneously audio files, works for Android, iOS, macOS and web. We now have new…
AudioPlayers package has enough specifications for a music player. You can retrieve music files from the web, get the duration of the file, and basic functionalities such as play, pause and stop. Let’s add this package to our app.
In this example, we are going to use play and stop functionalities and we want to play sound in a loop since we want it as a background sound.
Let’s create a MusicPlayer class.
Let’s discuss this class now. When we need to play background music, we are going to use this class but as we all expect that there must be only one background music at a time. We can play and stop background music or change it but when doing this we need to keep background music one and only. Otherwise, different music can be played at the same time, and this is the case that we want to avoid.
So this sentence is really a good match with one design pattern! Which is, singleton! So let’s make this class singleton and add basic functionalities.
Our MusicPlayer is ready. We can play a sound in a loop and stop it when needed. And since this class is a singleton, we can call it from different screens when needed.
Our play method needs a path to play a sound. With this, we can play different sounds when needed. Let’s import one sound, I have added this line to pubspec.yaml file.
This file is an ambiance sound file that is taken from a farm. We will play this as a background sound.
We have created 2 methods, we can call them when proper buttons pressed or when a certain case happened.
That’s all! Now you can call these methods when needed and your app has a background sound! You can give different sound files to play method as an argument since we have created our method with this capability.
That’s all for now. I hope that article will help you. If you have any questions or suggestions please leave me a comment. Thank you for your time. Hope to see you in the next articles!