harry
harry

Reputation: 85

Running Web Audio API in the background on iOS with Ionic Capacitor React for seamless MP3 looping?

I am currently developing a mobile app using Ionic Capacitor React and I need to play an MP3 file in a seamless and gapless loop in the background even when the app is closed. I have tried using the Web Audio API to achieve this, but I have encountered some issues.

When the app is in the foreground, the Web Audio API works perfectly, and the MP3 file loops seamlessly without any gaps. However, when the app is closed, the audio stops playing after a few seconds, and I cannot get it to resume without reopening the app.

I have tried using the Background Moode plugin to keep the app running in the background, but this does not seem to work either.

Has anyone else encountered this issue and found a solution? Is it possible to run the Web Audio API in the background on iOS with Ionic Capacitor React, and if so, how can I achieve seamless and gapless looping of an MP3 file?

 const createTrack = async () => {
    BackgroundMode.enable();
    BackgroundMode.disableBatteryOptimizations();
    const audioCtx = new window.AudioContext();
    const source = audioCtx.createBufferSource();
    const arrayBuffer = await fetch(
      '../assets/sounds/shortFan.mp3',
      ).then((res) => res.arrayBuffer());
      const audioBuffer = await audioCtx.decodeAudioData(arrayBuffer);
      
      source.buffer = audioBuffer;
      source.loop = true;
      source.connect(audioCtx.destination);
      source.start();
      audioCtx.resume();
}

here is some code ive been messing with the looop is perfect and gapless but once app is closed it stops playing. if i use an audio element it keeps playing in background but the loop has gaps in it.

Upvotes: 1

Views: 1211

Answers (1)

user93453
user93453

Reputation: 36

Since the iOS and Android device's operating system throttles background tasks and apps, in order to play a sequence of audio files while the app is in background mode or asleep you'll need to use a plugin that bridges your app to the device's native os api. The native os does support playing a queue of background audio.

You could of course write your own plugin to do this, but I've been successfully using the capacitor-plugin-playlist plugin with Ionic Capacitor.

Upvotes: 0

Related Questions