Adding Audio or Sounds in Flutter

Tiempo de lectura: 2 minutos

To add audio or sounds in Flutter, we’ll use the audioplayers library.

First, we install it:

flutter pub add audioplayers

Then, run flutter pub get in your terminal to install the dependency.

Organize Project Structure

If you haven’t already, organize your Flutter project so that you have a folder for assets like images and sounds. For example:

- my_flutter_app
  - android
  - ios
  - lib
  - assets
    - sounds
      - button_press.mp3
  - pubspec.yaml

Import the Audio Library

In the file where you plan to use sound (e.g., main.dart), import the audio library:

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

Create an AudioPlayer Instance

Inside your class (it can be a StatefulWidget), create an instance of AudioPlayer:

class MyApp extends StatelessWidget {
  final AudioPlayer audioPlayer = AudioPlayer();

  // Remaining app code
}

Set Up Files in assets

Make sure to configure the pubspec.yaml file to include the sounds folder:

flutter:
  assets:
    - assets/sounds/

Add Sound to Button Event

Inside your button widget, add sound playback in the onPressed event:

ElevatedButton(
  onPressed: () {
   audioPlayer.play(AssetSource('sounds/button_press.mp3'));
  },
  child: Text('Press for sound'),
)

Run the Application

Save your changes and run your Flutter application with flutter run from the terminal. When you press the button, you should hear the sound you configured.

You can also create a sound class to play it from all your buttons:

Step 1: Create a Utility File audio_util.dart

// audio_util.dart

import 'package:audioplayers/audioplayers.dart';

class AudioUtil {
  static final AudioPlayer _audioPlayer = AudioPlayer();

   static Future<void> playButtonPressSound() async {
    await _audioPlayer.play(AssetSource('sounds/button_press.mp3'));
  }
}

Step 2: Use the Utility in Your Application

// main.dart

import 'package:flutter/material.dart';
import 'audio_util.dart';

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

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Scaffold(
        appBar: AppBar(
          title: Text('Flutter Sound Button'),
        ),
        body: Center(
          child: ElevatedButton(
            onPressed: () async {
              await AudioUtil.playButtonPressSound();
            },
            child: Text('Press for sound'),
          ),
        ),
      ),
    );
  }
}

Now, you can use AudioUtil.playButtonPressSound() from anywhere in your application where you import audio_util.dart to play the sound when a button is pressed.

Here comes the complete API information: https://github.com/bluefireteam/audioplayers/blob/main/getting_started.md

Leave a Comment