Cannot play audio from background with just_audio_background flutter

38 views Asked by At

I am not able to play local audio from the background.

I have a Workmanager which runs periodically and should play a sound if necessary. This means that I start the audio from the background on the contrary of many examples which start the audio by clicking a play button for instance and then go in background.

Unfortunately the audio is not playing. I have followed the example code (https://github.com/ryanheise/just_audio/tree/minor/just_audio_background/example) with the only difference being the Workmanager.

import 'package:flutter/material.dart';
import 'package:just_audio/just_audio.dart';
import 'package:just_audio_background/just_audio_background.dart';

class AudioPlayerService {
  static const audioFilePath = 'assets/audio/notification.wav';
  final _playList = AudioSource.uri(
    Uri.parse("asset:///$audioFilePath"),
    tag: const MediaItem(
      id: 'notification',
      title: "Notification",
    ),
  );

  Future<void> playNotification() async {
    AudioPlayer? player;
    try {
      player = AudioPlayer();
      await player.setAudioSource(_playList);
      await player.play();
    } catch (e, stackTrace) {
      debugPrintStack(stackTrace: stackTrace);
    } finally {
      player?.dispose();
    }
  }
}

If I put the code behind a button on a Widget, the audio plays just fine.

AndroidManifest.xml

<uses-permission android:name="android.permission.WAKE_LOCK" />
<uses-permission android:name="android.permission.FOREGROUND_SERVICE" />
<uses-permission android:name="android.permission.FOREGROUND_SERVICE_MEDIA_PLAYBACK"/>

<!-- just_audio_background -->
<activity
        android:name="com.ryanheise.audioservice.AudioServiceActivity"
...
    <service
        android:name="com.ryanheise.audioservice.AudioService"
        android:foregroundServiceType="mediaPlayback"
        android:exported="true">
        <intent-filter>
            <action android:name="android.media.browse.MediaBrowserService" />
        </intent-filter>
    </service>

    <receiver
        android:name="com.ryanheise.audioservice.MediaButtonReceiver"
        android:exported="true">
        <intent-filter>
            <action android:name="android.intent.action.MEDIA_BUTTON" />
        </intent-filter>
    </receiver>
0

There are 0 answers