Flutter play beep sound

To play a beep sound in Flutter, you can use the “audioplayers” package. First, add the following dependency to your pubspec.yaml file:

dependencies:
  audioplayers: ^0.20.1

After adding the dependency, run flutter pub get command to fetch the package.

Next, import the audioplayers package in your Dart file:

import 'package:audioplayers/audioplayers.dart';

To play a beep sound, you can use the following code:

AudioPlayer advancedPlayer = AudioPlayer();

await advancedPlayer.setAsset('assets/sounds/beep.wav');
await advancedPlayer.play();

Make sure you have a “beep.wav” file in the “assets/sounds” directory of your project. To add the sound file, update the pubspec.yaml file as follows:

flutter:
  assets:
    - assets/sounds/

Now you can call the above code to play the beep sound whenever needed. Remember to use async/await as the audio playback is an asynchronous operation.

For example, if you want to play the beep sound when a button is pressed, you can use the following code:

ElevatedButton(
  onPressed: () async {
    AudioPlayer advancedPlayer = AudioPlayer();

    await advancedPlayer.setAsset('assets/sounds/beep.wav');
    await advancedPlayer.play();
  },
  child: Text('Play Beep Sound'),
)

This button’s onPressed event will trigger the playback of the beep sound when pressed.

Leave a comment