1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

Flutterのaudioplayersで「Attempt to perform seekTo in wrong state」が出た場合の対処方法

Posted at

Flutterのaudioplayersで「Attempt to perform seekTo in wrong state」が出た場合の対処方法

使用していたライブラリ及びバージョンは下記の通り

  • audioplayers: ^0.20.1

対処

むやみにAudioPlayerをインスタンス化しなければ大丈夫っぽい
音を鳴らすごとにインスタンス作ってしまっていたのが原因

音(サウンドエフェクト)を出す毎にインスタンスを作っていた時は40~50回目で「Attempt to perform seekTo in wrong state」というエラーが出てしまうようになりました

インスタンス化をしない場合120回再生しても大丈夫でした

インスタンス化を行わない場合の弊害

同時に2つの音が出せなくなる
AudioPlayerをプールして解決

プールすることで、インスタンス数分、同時に音が出せるようになりました。
めでたしめでたし。

下記クソコードを貼っておきます

SoundManagerPool.dart
import 'dart:async';
import 'package:audioplayers/audioplayers.dart';

class SoundManagerPool {
  int playIndex = 0;
  List<SoundManager> managers = [];

  SoundManagerPool(int managerCount) {
    for (int i = 0; i < managerCount; i++) {
      managers.add(SoundManager());
    }
  }

  Future<void> loadSound(List<String> fileNames) async {
    for (var manager in managers) {
      await manager.loadSound(fileNames);
    }
    return;
  }

  Future<void> playSound(String path) async {
    await managers[playIndex].playSound(path);
    playIndex++;
    if (managers.length == playIndex) {
      playIndex = 0;
    }
    print("playIndex" + playIndex.toString());
    return;
  }
}

class SoundManager {
  late AudioPlayer advancedPlayer;
  late AudioCache audioCache;
  SoundManager() {
    advancedPlayer = AudioPlayer();
    audioCache = AudioCache(fixedPlayer: advancedPlayer);
  }

  Future<void> loadSound(List<String> fileNames) async {
    await audioCache.loadAll(fileNames);
    return;
  }

  Future<void> playSound(String path) async {
    await audioCache.play(path, mode: PlayerMode.LOW_LATENCY);
    return;
  }
}

1
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?