How to Play a Custom Sound in Your Mobile App

Posted: October 15th, 2015Author:

Audio_with_JS

To make your app more interactive and stand out from the competition, one nice option is to play a nice sound file in the background when an event occurs.

You can easily add a custom sound to an app you are building in Appery.io and play it using the standard HTML5 Audio component. As you can always customize any app with custom JavaScript, you can start and stop playing the sound via JavaScript. I’m going to show you how to do this in your Appery.io app.

Adding new JavaScript

The first step is to add the custom JavaScript that will play the sound file. Open your app in the App Builder, go to Create New > JavaScript and add the following JavaScript code:

How to play the sound

When you need to play a sound, simply use this JavaScript code to reference and play the sound:

In this code you invoke the PlayTrack() function by passing the URL to a sound file as a parameter.

The audio file is stored on the server, not locally.

This code can be invoked on any event in the app. For example, on the page show event. Or it can be simply invoked on a button click event.

How to stop playing the sound

To stop playing the sound file you will use the following JavaScript code:

The example that I have showed you so far used a sound file that is stored somewhere on the Internet. You can easily upload a file directly into your app and play it. This means your app can be offline and play the sound.

How to upload the sound file to the app

Open the Source view in the App Builder.

Upload your sound file (eg. Ding.mp3) into WEB_RESOURCES -> files -> resources.

Audio_example

Source view of the app

And now you can play sound by invoking the function you used before PlayTrack() like this:

For Libraries 3.0 since the app structure of project folders has been changed in it.

You will need to move all your sound files to the ../app folder:

Lib3_audio_file

Library 3.0 Source view

and invoke PlayTrack() function to play your file this way:

The above code will play the sound file you uploaded to your app. With the sound file uploaded to the app, your app will be able to play the file whether it’s online or offline.

In this post I have showed you how easy it is to upload and play a custom sound file in your app.

If you like this and want to start building apps fast, it’s easy to sign up and start developing for free.