Flutter: Unable to access ressource for audioplayers package

919 Views Asked by At

I try to play a local mp3 audio file on onPressed()

The function looks like this:

playLocal() async {
  await audioPlayer.play('assets/audio/test.mp3', isLocal: true);
}

The file is located here:

assets folder structure

pubspec.yaml:

flutter:
  uses-material-design: true
  assets:
    - assets/audio/test.mp3

The audioplayers error:

[ERROR:flutter/lib/ui/ui_dart_state.cc(177)] Unhandled Exception: PlatformException(Unexpected error!, Unable to access resource, java.lang.RuntimeException: Unable to access resource
1

There are 1 best solutions below

1
On

This is the class i' m using.

import 'dart:io';

import 'package:audioplayers/audio_cache.dart';
import 'package:audioplayers/audioplayers.dart';
import 'package:flutter/foundation.dart';

void audioPlayerHandler(AudioPlayerState value) => null;

class PlaySound {
  final AudioPlayer _audioPlayer = AudioPlayer(mode: PlayerMode.LOW_LATENCY);
  final AudioCache _audioCache = AudioCache();

  static PlaySound _instance;
  static PlaySound get instance {
    _instance ??= PlaySound._init();
    return _instance;
  }

  PlaySound._init();

  void playLocalAsset({String sound}) async {
    if (!kIsWeb && Platform.isIOS) {
      //https://stackoverflow.com/questions/61263458/flutter-fatal-error-callback-lookup-failed-with-audioplayers-package
      await _audioPlayer.monitorNotificationStateChanges(audioPlayerHandler);
    }
    if (_audioCache != null) {
      await _audioCache.play(sound);
    }
  }

  void playFromUrl({String url}) async {
    await _audioPlayer.play(url);
  }
}

This is pubspec.yaml

assets:
 - assets/sound/

Just call it like this:

await PlaySound.instance.playLocalAsset(sound: 'sound/yourfile.mp3');