I’ve made a free template available for you to easily duplicate: Access here
1. Step: create two app state
1: Name: audioRef DataType: JSON Persisted: True
we will initialise and cache the background music here
2:
Name: Music DataType: Boolean Persisted: True Default Value: True
2. Step: Initialize the background music
Here is two solution to Initialize the background music:
1: Initialize from an url (this action will cache the audio file too, to save bandwidth)
Action Name: initializeAudioPlayer
Argument Name: url Type: audiopath not nullable
Pubspec dependencies:
just_audio
dio
import 'package:just_audio/just_audio.dart';
import 'package:path_provider/path_provider.dart';
import 'package:dio/dio.dart';
import 'dart:io';
Future<void> initializeAudioPlayer(String url) async {
final appDocDir = await getApplicationDocumentsDirectory();
final filePath = '${appDocDir.path}/downloadedAudio.mp3';
try {
// Download the file
final dio = Dio();
await dio.download(url, filePath);
AudioPlayer audioPlayer = AudioPlayer();
await audioPlayer.setFilePath(filePath); // Set the file path of the audio
// Save the audio player instance to app state
FFAppState().audioRef = audioPlayer;
} catch (e) {
print("Error downloading or playing audio: $e");
}
}
2: Initialize from an asset:
Action Name: initializeAudioPlayerAsset
Argument Name: assetPath Type: audiopath not nullable
import 'package:just_audio/just_audio.dart';
import 'package:path_provider/path_provider.dart';
import 'package:dio/dio.dart';
import 'dart:io';
Future<void> initializeAudioPlayerAsset(String assetPath) async {
try {
AudioPlayer audioPlayer = AudioPlayer();
await audioPlayer.setAsset(assetPath); // Set the asset path of the audio
// Save the audio player instance to app state
FFAppState().audioRef = audioPlayer;
} catch (e) {
print("Error initializing or playing audio from asset: $e");
}
}
Use one of these actions within an on-page load action on your Entry page.
Use a condition to call it only if the appstate is empty.
Important:
If you're planning to add this as an on-page load action, it's crucial to begin with a wait or delay action of at least 200 milliseconds. This ensures that the page fully loads before the code is executed.
3. Play the music on loop
Action Name: playAudio
no arguments here
Pubspec dependencies:
just_audio
import 'package:just_audio/just_audio.dart';
Future<void> playAudio() async {
AudioPlayer audioPlayer = FFAppState().audioRef;
if (audioPlayer != null) {
await audioPlayer
.setLoopMode(LoopMode.one); // Set the player to loop the current track
await audioPlayer.setVolume(0.2);
await audioPlayer.play(); // Play the audio
}
}
After your initialized the music, use a condition to play it, if music turned on, play the audio. You can use this logic with a toggle and with the next action, to turn on/off permanently the background music.