DEV Community

jeremykuang
jeremykuang

Posted on • Updated on

In App Background Audio Player on OutSystems Mobile App

Requirements

An audio player that will continue playing in the background (whether the users exits the app or navigates to different screens within the app)

Problem

For OutSystems Mobile App, React is used for its frontend. For React developers, one would probably develop in a way where the audio player component will be placed at the top level, so that when the app traverses from page to page, the audio player will not be re-rendered.

In OutSystems, one would think of placing the audio player component in the layout web block or menu (navigation) web block, where it will most likely be the common block used through all the screens. However, the whole page (Layout Web Block and its components within) re-renders with each screen transition. Thus, the audio player also re-renders and the audio stops playing when the screen transits to another.

Compromise

Initially I was thinking of proposing a compromise to the stakeholders and asked if it was acceptable to have the audio "pause" as the screen transits and the audio "continue" to play when the new screen transits in. This will mean the app will probably have to store the last played time in the localStorage in the On Destroy event (when the transition to the new Screen ends). Then in the new screen's On Render Event, retrieve the last played time from the localStorage, seek to the last played time and then play the audio.

Solution

As I was testing the "compromise", I remembered and that the React root is the "top-level" <div> and not <body>. Then, it was clear to me that if I can place the Audio Player outside of the React root, which would always re-render, the Audio Player can keep on playing so as long as the page does not refresh.

The root React element in OutSystems is <div id="reactContainer">. You can probably put in the following Javascript in the OnApplicationReady event to append the Audio Player element in the save level as <div id="reactContainer"> (append to <body>).

var jwPlayerElement = document.createElement('div')
jwPlayerElement.id = 'jw-player';
document.getElementsByTagName('body')[0].appendChild(jwPlayerElement);

var jwPlayer = jwplayer('jw-player');
jwPlayer.setup({
    sources: [
        {file: "https://domain.com/playlist.m3u8"}
    ]
})
Enter fullscreen mode Exit fullscreen mode

Change the initialisation codes according to your Audio Player's requirements. As JWPlayer allows the retrieval of the instance through jwplayer('jw-player') at any location, I can just call it again to change the source or call its methods (play, pause, etc.) If your player does provide such a functionality, you may have to include a script to store the audio player instance to a global variable.

TODO

  • Image and Diagrams to explain the steps better.

  • Sample OutSystems OML file.

Top comments (0)