flutter add sound button code example

Example: flutter button playing sound

void main() => runApp(HomePage());

class HomePage extends StatefulWidget {
  
  _HomePageState createState() => _HomePageState();
}

class _HomePageState extends State<HomePage> {
  AudioCache _audioCache;

  
  void initState() {
    super.initState();
    // create this only once
    _audioCache = AudioCache(prefix: "audio/", fixedPlayer: AudioPlayer()..setReleaseMode(ReleaseMode.STOP));
  }

  
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Scaffold(
        appBar: AppBar(title: Text("Music play")),
        body: RaisedButton(
          onPressed: () => _audioCache.play('my_audio.mp3'),
          child: Text("Play Audio"),
        ),
      ),
    );
  }
}

Tags:

Dart Example