How to Play Sound from Assets Folder in Flutter App

In this example, we are going to show you how to play sounds such as MP3, WAV from the Asset folder in Flutter App. Previously, we have shown to make a full functioning audio player with play, pause, stop, seek, jump, duration indicator, etc. See the example below:

First, you need to add audioplayer Flutter package in your project by adding the following lines in pubspec.yaml file.

dependencies:
  flutter:
    sdk: flutter
  audioplayers: ^0.20.1

Index asset folder in pubspec.yaml file.

flutter:

  # The following line ensures that the Material Icons font is
  # included with your application, so that you can use the icons in
  # the material Icons class.
  uses-material-design: true

  # To add assets to your application, add an assets section, like this:
  assets:
    - assets/audio/

Add, sound file in asset folder:

import 'dart:typed_data';
import 'package:audioplayers/audioplayers.dart';
import 'package:flutter/services.dart';
AudioPlayer player = AudioPlayer();
String audioasset = "assets/audio/ambulance_sound.mp3";
ByteData bytes = await rootBundle.load(audioasset); //load sound from assets
Uint8List  soundbytes = bytes.buffer.asUint8List(bytes.offsetInBytes, bytes.lengthInBytes);
int result = await player.playBytes(soundbytes);
if(result == 1){ //play success
    print("Sound playing successful.");
}else{
    print("Error while playing sound."); 
}

Here, we read the sound file from asset folder and load it as Unit8List, and we use audioplayer package to play it. You don't neet any permission to play the sound.  You can read more abut playing audio with code example: How to Play Audio in Flutter | Full Audio Player Code Example

int result = await player.stop();

// You can pasue the player
// int result = await player.pause();

if(result == 1){ //stop success
    print("Sound playing stopped successfully.");
}else{
    print("Error on while stopping sound."); 
}

import 'dart:typed_data';
import 'package:audioplayers/audioplayers.dart';
import 'package:flutter/services.dart';
import 'package:flutter/material.dart';

void main() {
  runApp(MyApp());
}

class MyApp extends StatelessWidget{
  @override
  Widget build(BuildContext context) {
     return MaterialApp(
         home: Home()
      );
  }
}

class Home extends  StatefulWidget {
  @override
  State<Home> createState() => _HomeState();
}

class _HomeState extends State<Home> {

  AudioPlayer player = AudioPlayer();

  @override
  Widget build(BuildContext context) {
    return Scaffold(
         appBar: AppBar(
            title: Text("Play Sound in Flutter App"),
            backgroundColor: Colors.redAccent
         ),
         body: Container( 
               margin: EdgeInsets.only(top:50),
               child: Wrap( 
                spacing: 10,
                children: [
                    ElevatedButton.icon(
                      onPressed: () async {
                              String audioasset = "assets/audio/ambulance_sound.mp3";
                              ByteData bytes = await rootBundle.load(audioasset); //load sound from assets
                              Uint8List  soundbytes = bytes.buffer.asUint8List(bytes.offsetInBytes, bytes.lengthInBytes);
                              int result = await player.playBytes(soundbytes);
                              if(result == 1){ //play success
                                  print("Sound playing successful.");
                              }else{
                                  print("Error while playing sound."); 
                              }
                      }, 
                      icon: Icon(Icons.play_arrow),
                      label:Text("Play")
                    ),

                    ElevatedButton.icon(
                      onPressed: () async {
                          int result = await player.stop();

                          // You can pasue the player
                          // int result = await player.pause();

                          if(result == 1){ //stop success
                              print("Sound playing stopped successfully.");
                          }else{
                              print("Error on while stopping sound."); 
                          }
                      }, 
                      icon: Icon(Icons.stop),
                      label:Text("Stop")
                    ),
                          
                 ],
               )
          
          )
    );
  } 
}

In this way, you can play sound from the assets folder in Flutter app. 

No any Comments on this Article


Please Wait...