2
3

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 5 years have passed since last update.

Flutterでassets内の音声ファイルを再生する

2
Posted at

はじめに

Flutterでassets内の音声ファイルを再生するのに、少し手間取ったのでメモとして残しておきます。

前提

次のプラグインを使用

  • audioplayers : 0.13.7

音声ファイルはassets/soundsに配置

コード

pubspec.yamlに次を追記します。

pubspec.yaml
dependencies:
  audioplayers: ^0.13.7

flutter:
  assets:
    - assets/sounds/

ローカルファイルのみ再生可能なため、アセットからローカルファイルを作成するSoundManagerクラスを作成します。

class SoundManager {
  AudioPlayer audioPlayer = AudioPlayer();
  Future playLocal(String localFileName) async {
    final dir = await getApplicationDocumentsDirectory();
    final file = File('${dir.path}/$localFileName');
    if (!file.existsSync()) {
      final soundData = await rootBundle.load('assets/sounds/$localFileName');
      final bytes = soundData.buffer.asUint8List();
      await file.writeAsBytes(bytes, flush: true);
    } 
    await audioPlayer.play(file.path, isLocal: true);
  }
}

あとは、次の方法で再生できます。

final SoundManager soundManager = SoundManager();
soundManager.playLocal('$fileName.wav');

参考

Playing from assets · Issue #5 · rxlabz/audioplayer · GitHub
avoid_slow_async_io

2
3
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
2
3

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?