flutter button playing sound code example

Example: flutter button playing sound

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

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

class _HomePageState extends State<HomePage> {
  AudioCache _audioCache;

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

  @override
  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:

Misc Example