1

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)

spydon
  • 9,372
  • 6
  • 33
  • 63
Andi Qu
  • 186
  • 1
  • 10
  • Wow I deleted the directory. :) I used the latest audioPlayers plugin, and then I loaded 4 same instances of one Audio File. Just duplicate the same file and add it to assets. Than I would create 4 instances of AudioPlayer, and play them in circles. – Tree Jun 27 '18 at 18:46
  • You have to run it in release mode or on device, as well. – Tree Jun 27 '18 at 18:47

0 Answers0