Can anybody tell me how to use this latest library to play a single audio file present in the asset folder of the root of flutter? The code sample of this library on pub.dev is quite difficult to understand
CodePudding user response:
First create an instance of AudioPlayer
class.
final player = AudioPlayer();
then add asset file in player.setSource
method.
await player.setSource(AssetSource('sounds/coin.wav'));
For more Getting Started documentation
CodePudding user response:
It's as simple as the following snippet. Where click.mp3
is inside the assets
folder.
final player = AudioPlayer();
player.play(AssetSource('click.mp3')),
A complete example:
import 'package:audioplayers/audioplayers.dart';
import 'package:flutter/material.dart';
void main() {
runApp(const MyApp());
}
class MyApp extends StatelessWidget {
const MyApp({Key? key}) : super(key: key);
@override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Flutter Demo',
theme: ThemeData(
primarySwatch: Colors.blue,
),
home: const MyHomePage(),
debugShowCheckedModeBanner: false,
);
}
}
class MyHomePage extends StatefulWidget {
const MyHomePage({Key? key}) : super(key: key);
@override
State<MyHomePage> createState() => _MyHomePageState();
}
class _MyHomePageState extends State<MyHomePage> {
AudioPlayer? _player;
@override
void dispose() {
_player?.dispose();
super.dispose();
}
void _play() {
_player?.dispose();
final player = _player = AudioPlayer();
player.play(AssetSource('click.mp3'));
}
@override
Widget build(BuildContext context) {
return Scaffold(
body: Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: const [
Text(
'Click on the play button to play a sound',
),
],
),
),
floatingActionButton: FloatingActionButton(
onPressed: _play,
tooltip: 'Play',
child: const Icon(Icons.volume_up),
),
);
}
}