by @kodeazy
flutter How to create an audio player from local path and play?
In this blog we will discuss on how to add audio file from local path and play them once button is clicked.
Below are the steps to add the audio file in app and play
- Add the dependecy in
pubspec.yaml
file. - Create a folder and add audio files inside the project
- Now index
asset
folder insidepubspec.yaml
. -
create A Button and add the
AudioCache
class to play the file when button is clicked.Add the dependecy in
pubspec.yaml
file.dev_dependencies: flutter_test: sdk: flutter audioplayers: ^0.17.4
create a folder and add audio files inside the project
Project folder
└── assets
└── test.mp3Here we created a folder called
assets
inside the project folder and addedtest.mp3
file inside it.Now index
asset
folder insidepubspec.yaml
.flutter: uses-material-design: true assets: - assets/text.mp3
create A Button and add the
AudioCache
class to play the file when button is clicked.Below is an example code to play audio.
final player = AudioCache(); player.play('text.mp3');
Below is a sample program to play music on button click.
import 'package:flutter/material.dart'; import 'package:audioplayers/audio_cache.dart'; void main() { runApp(const MyApp()); } class MyApp extends StatelessWidget { const MyApp({Key? key}) : super(key: key); @override Widget build(BuildContext context) { return MaterialApp( home: Scaffold( appBar: AppBar(title: Text("Audio Player Example"),), body: Center( child: FlatButton( onPressed: (){ final player = AudioCache(); player.play('text.mp3'); }, child: Text("Click here"), ), ), ), ); } }