I am making a metronome app in Flutter. I used the AudioPlayers plugin along with the Metronome class from the quiver.async library. Here is the part of the code that I used to achieve this:
import 'dart:async' show Future, StreamSubscription;
import 'dart:io' show File;
import 'package:flutter/services.dart' show ByteData, rootBundle;
import 'package:path_provider/path_provider.dart' show getTemporaryDirectory;
import 'package:audioplayers/audioplayer.dart' show AudioPlayer;
import 'package:quiver/async.dart' show Metronome;
...
File _soundFile;
/// List of possible sounds
List<String> _sounds = ['bottle', 'click', 'tamborine'];
int _soundIndex = 0;
/// Tempo of the metronome
static int tempo = 100;
bool _isPlaying = false;
Metronome _metronome = Metronome.periodic(Duration(milliseconds: (60000 / tempo).floor()));
StreamSubscription<DateTime> _subscription;
Future<ByteData> _loadSound() async {
return await rootBundle.load('assets/${_sounds[_soundIndex]}.mp3');
}
void _writeSound() async {
_soundFile = File(
'${(await getTemporaryDirectory()).path}/${_sounds[_soundIndex]}.mp3');
await _soundFile.writeAsBytes((await _loadSound()).buffer.asUint8List());
}
void _playLocal() async {
final AudioPlayer _audioPlayer = AudioPlayer();
AudioPlayer.logEnabled = false;
await _audioPlayer.play(_soundFile.path, isLocal: true);
}
/// The actual method that plays the metronome
void playMetronome() {
if (_soundFile == null) {
_writeSound();
}
setState(() {
if (_isPlaying) {
_subscription.cancel();
_isPlaying = false;
} else {
_subscription = _metronome.listen((d) => _playLocal());
_isPlaying = true;
}
});
}
Sometimes though, the metronome lags just a bit, but more than enough to be noticeable. I can't tell if it's because of the AudioPlayer or the Metronome. How can I fix this?
(The AudioPlayers plugin that I'm using is this one)