Customize Consent Preferences

We use cookies to help you navigate efficiently and perform certain functions. You will find detailed information about all cookies under each consent category below.

The cookies that are categorized as "Necessary" are stored on your browser as they are essential for enabling the basic functionalities of the site. ... 

Always Active

Necessary cookies are required to enable the basic features of this site, such as providing secure log-in or adjusting your consent preferences. These cookies do not store any personally identifiable data.

No cookies to display.

Functional cookies help perform certain functionalities like sharing the content of the website on social media platforms, collecting feedback, and other third-party features.

No cookies to display.

Analytical cookies are used to understand how visitors interact with the website. These cookies help provide information on metrics such as the number of visitors, bounce rate, traffic source, etc.

No cookies to display.

Performance cookies are used to understand and analyze the key performance indexes of the website which helps in delivering a better user experience for the visitors.

No cookies to display.

Advertisement cookies are used to provide visitors with customized advertisements based on the pages you visited previously and to analyze the effectiveness of the ad campaigns.

No cookies to display.

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:

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
flutter pub add audioplayers
flutter pub add audioplayers
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:

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
- my_flutter_app
- android
- ios
- lib
- assets
- sounds
- button_press.mp3
- pubspec.yaml
- my_flutter_app - android - ios - lib - assets - sounds - button_press.mp3 - pubspec.yaml
- 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:

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
import 'package:flutter/material.dart';
import 'package:audioplayers/audioplayers.dart';
import 'package:flutter/material.dart'; import 'package:audioplayers/audioplayers.dart';
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:

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
class MyApp extends StatelessWidget {
final AudioPlayer audioPlayer = AudioPlayer();
// Remaining app code
}
class MyApp extends StatelessWidget { final AudioPlayer audioPlayer = AudioPlayer(); // Remaining app code }
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:

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
flutter:
assets:
- assets/sounds/
flutter: assets: - assets/sounds/
flutter:
  assets:
    - assets/sounds/

Add Sound to Button Event

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

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
ElevatedButton(
onPressed: () {
audioPlayer.play(AssetSource('sounds/button_press.mp3'));
},
child: Text('Press for sound'),
)
ElevatedButton( onPressed: () { audioPlayer.play(AssetSource('sounds/button_press.mp3')); }, child: Text('Press for sound'), )
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

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
// 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'));
}
}
// 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')); } }
// 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

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
// 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'),
),
),
),
);
}
}
// 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'), ), ), ), ); } }
// 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

0

Leave a Comment