I wanted to build on the answer from ltk and provide an example. This was a simple app that I created as part of a Udemy course where you create a Xylophone app:
import 'package:audioplayers/audioplayers.dart';
import 'package:flutter/material.dart';
void main() {
runApp(const App());
}
class App extends StatelessWidget {
const App({super.key});
// The default data type for a List of Objects is <Map<String, Object>>.
// However, it is important to specify <Map<String, dynamic>> as the data
// type otherwise you will get errors when you try to reference the Object
// properties inside the Expanded widget.
// See https://stackoverflow.com/a/67231333/9453009
static final soundButtons = <Map<String, dynamic>>[
{'color': Colors.red, 'number': 1},
{'color': Colors.orange, 'number': 2},
{'color': Colors.yellow, 'number': 3},
{'color': Colors.green, 'number': 4},
{'color': Colors.teal, 'number': 5},
{'color': Colors.blue, 'number': 6},
{'color': Colors.purple, 'number': 7},
];
void playSound(int soundNumber) async {
final player = AudioPlayer();
await player.play(AssetSource('note$soundNumber.wave'));
}
// This widget is the root of your application.
@override
Widget build(BuildContext context) {
return MaterialApp(
home: Scaffold(
backgroundColor: Colors.black,
body: SafeArea(
child: Column(
crossAxisAlignment: CrossAxisAlignment.stretch,
children: [
for (int i = 0; i < soundButtons.length; i++) ...[
Expanded(
child: TextButton(
onPressed: () {
playSound(soundButtons[i]['number']);
},
style: TextButton.styleFrom(
backgroundColor: soundButtons[i]['color'],
),
child: const Text(''),
),
),
],
],
),
),
),
debugShowCheckedModeBanner: false,
);
}
}
NOTE: I could not get the sound files to work due to some build issues with Linux, but I think this is how you would use the audioplayers package.