DEV Community

DailyFlutter.Monster
DailyFlutter.Monster

Posted on • Originally published at dailyflutter.monster

Flutter Audiobook Player in 50 lines of code

Intro

How much can you do with 60 lines of code? Depends how good you are, also more importantly depends how good your language/framework is. While this won't be a tutorial on making super complicated quines of try to code golf until to the limit, I still found it worth sharing how easy and quick you can set up an audiobook player that plays books from librivox that can work on ios, android and web (copy and paste code at the bottom).

Tutorial

Installing Packages

For this tutorial I will be installing the package assets_audio_player for playing the audio. (In my case I will be also creating it as a web app so I will aslo install assets_audio_player_web).

Alt Text

Show me the code

In main.dart delete everything except for the main funtion, then create a statefull widget MyApp.

in MyAppState we add the variables for keeping track of time and if the audio is paused or playing. I also added the url that I will be opening here.

Alt Text

In the build method we want to first make a material app, (I dont like the debug banner so I set debugShowCheckedModeBanner: false)

Alt Text

This MaterialApp's home will be a Scaffold with a Center widget. The center widget will have a Colum so that we can add our video's playback time and the play/pause button. This should be placed in the center of the screen so we set CrossAxisAllignment and MainAxisAllignment to center aswell.

Alt Text

Now to build the audiobook player part. First, onto the simple stuff, we will create a Text widget that displays the time:

Alt Text

Next we add the AudioWidget (you willl need to import assets_audio_player). The paramenters we have to set are:

  • 'audio:' This takes in the audio's input source (can be from network or from asset)
  • 'play:' bool that stores the state
  • 'child': this where you would add your button or more elaboorate widget
  • 'onPositionChanged:' listens for changes in the audio position (c is current time and d is duration)
  • 'onReadyToPlay': listens for when the audio is ready to be played

For this tutorial my setup ended up being:

Alt Text

This came out to 52 lines and if we run it we get:

Alt Text

Alt Text

Conclusion

I hope you have enjoyed reading along and that you can make something much cooler than I did.

As promised here is the copy and paste code:

(source code)

Top comments (0)