Home > Software design >  What is the fastest way to play sound after pressing a button on flutter?
What is the fastest way to play sound after pressing a button on flutter?

Time:07-13

I don't know much about Flutter. I don't know how to play a sound the fastest. The fastest method I've tried has a delay of 250 milliseconds. All I want to do is have a button make a sound. I guess what I need to do is to cache the audio, but I don't have enough information for that. I'll be happy if you can help me.

CodePudding user response:

Simple solution for playing a file already defined in assets is using AudioCache. Library: https://pub.dartlang.org/packages/audioplayers. More about AudioCache After adding library to pubspec.yaml, import required class:

import 'package:audioplayers/audio_cache.dart';

add an asset in the same file and place the file with sound to assets folder (if you don't have this folder, create it)

assets:
- assets/sound_alarm.mp3

then add this code:

static AudioCache player = new AudioCache();
const alarmAudioPath = "sound_alarm.mp3";
player.play(alarmAudioPath);

CodePudding user response:

Here's what to do with help from mortiz's answer:

pubspec.yaml, import required class:

dependencies:
      audioplayers: ^0.20.1 # Not "1.0.1". Because audioplayers/audio_cache.dart does not exist.

import required class:

import 'package:audioplayers/audioplayers.dart';

add an asset in the same file and place the file with sound to assets folder (if you don't have this folder, create it)

assets:
- assets/sound_alarm.mp3

then add this code:

static AudioCache player = new AudioCache();
const alarmAudioPath = "sound_alarm.mp3";

To cache the audio we need to overwrite this in the initstate method:

@override
  void initState() {
    player.load(alarmAudioPath );
  }

Then we can play the sound with this function:

player.play(alarmAudioPath );
  • Related