颤振的音频播放器或节拍器滞后

时间:2018-06-26 17:20:45

标签: dart flutter

我正在Flutter中制作节拍器应用程序。我将AudioPlayers插件与 quiver.async库中的Metronome类。这是我用来实现此目的的代码部分:

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;
        }
    });
}

有时,节拍器仅滞后一点,但足以引起注意。我不知道是因为AudioPlayer还是节拍器。我该如何解决?

(我正在使用的AudioPlayers插件为this one

0 个答案:

没有答案