Tag Archives: sound

Play audio in an iOS app with Xamarin

This tutorial explains how to play audio files in the background in an iOS app. An audio file can play when a screen loads or when an event occurs (such as a button press or change in a variable’s value). The example app in this tutorial will play a sound when a button is pressed. We will also look at how to use the Vibrate function in an iPhone to make the phone vibrate as well as playing a sound.

Here is what this app will look like:

ia_app

Step 1 

Open Xamarin and click File > New Solution. Then select iOS App and SingleView App as the project template. Click Next.

ia1

Step 2

Give your new app a name and select a target iOS version. Click Next. On the following screen, confirm the project and solution name and then click Create.

ia2

Step 3

When the solution opens, right-click on the project folder. Select Add > New Folder.

ia3

Give the new folder the name Sounds.

ia3b

Step 4

Right-click on the new Sounds folder and select Add > Add files from folder.

ia4

Step 5

Navigate to the folder which contains the audio file(s) you wish to use in your app. Click Open.

ia4b

Step 6 

Select the audio files you wish to include in the project (for this example, we will use an MP3 file called mysound.mp3). Click OK.

ia5

Then select Copy the file to the directory and click OK. This file will be copied to the project’s Sounds folder. You should then be able to see the audio file in the Sounds folder within the project folder from the Solution panel.

ia5b

Step 7

Right-click on the audio file in the Sounds folder. Select Build Action and set to BundleResource (if this does not work during testing, try selecting Content instead).

ia6

Step 8

Open the Main.storyboard file. Change the View to your desired iPhone/iPad model. Drag three Button elements on to the screen as shown below. Give the first button a Name of playSoundButton and the text value ‘Play sound’. Give the second button a Name of playSoundVibrateButton and the text value ‘Play sound and vibrate’. Give the third button a Name of vibrateButton and the text value ‘Vibrate’. Save the file.

ia7
Click the image to see a larger version.

Step 9

Open the ViewController.cs file and add the following two highlighted lines of code. The first two highlighted lines allow us to access audio tools and lower-level classes. url defines where the location and name of the audio file, while mySound is the name of the variable holding the sound file.

ia8
Click the image to see a larger version.

Step 10

Now add the following two highlighted lines of code in the ViewDidLoad method. Here we define the location and filename of the audio file as well as directing the mySound variable to use this audio file. Replace mysound.mp3 with the name of your sound file.

ia9
Click the image to see a larger version.

Step 11 

Now create a TouchUpInside event for each of the three buttons in the ViewDidLoad method. Inside the new methods for each TouchUpInside event, add the lines of code shown below.

  • SystemSound.PlaySystemSound(); will just play the sound
  • SystemSound.PlayAlertSound(); will play the sound and vibrate the phone
  • SystemSound.Vibrate.PlaySystemSound(); will just vibrate the phone
ia10
Click the image to see a larger version.

That’s it! Now go and test the app!

Play audio in an Android app with Xamarin

This tutorial explains how to play audio in an Android app made in Xamarin. The audio can be played when a screen loads or when an event occurs such as a button click or change in a variable’s value. For this tutorial, we will play a sound when a button is tapped.

au_app

Step 1

Start by creating a new app solution in Xamarin (click File > New Solution). Select Android App as the project template. Click Next.

au1

Give the new app a name. Then click Next.

au2

Confirm the solution and project name, Make sure you specify a folder to store your project files in and then click Create.

au3

Step 2

Open the Main.axml file (in Resources > layout). Delete the button already there. Save the file.

au4

Step 3 

Open the MainActivity.cs file and delete the highlighted lines of code (these lines for the button are not needed anymore as we won’t be using the default button).

au5

Step 4 

Right-click on the Resources folder. Select Add > New Folder.

au6

Give the new folder the name ‘raw’ and then press Enter.

au6b

Step 5

Select the new ‘raw’ folder and right-click it. Then click Add > Add files from folder.

au7

Step 6

Navigate to the folder which contains the audio file(s) you wish to use in your app. Click Open.

au7b

Step 7

Select the audio files you wish to include in the project (for this example, we will use an MP3 file called mysound.mp3). Click OK.

au8

Then select Copy the file to the directory and click OK. This file will be copied to the project’s raw folder. You should then be able to see the audio file in the raw folder from the Solution panel.

au8b

Step 8

Open the Main.axml file again and drag a Button element from the Toolbox onto the phone screen. Change the button’s Id value to @+id/playButton. Then change its Text value to Play Sound. Save this file.

au9

Step 9

Open the MainActivity.cs file again. Add the following highlighted line of code to the top section of the existing code. This will give us access to Android.Media.

au10
Click the image to see a larger version.

Step 10

Add the following two highlighted lines of code to the MainActivity.cs file to define the MediaPlayer element and to include the audio file in the code. Replace mysound with the name of your audio file (there is no need to include the .mp3 extension).

au11
Click the image to see a larger version.

Step 11

Now add the following two highlighted lines of code to define the Button element and access the playButton button from the screen.

au12
Click the image to see a larger version.

Step 12

Now add a click event for the button inside the OnCreate method. As you type playButton.Click+= and press the spacebar key you will see a list of options. You should see the option to create the PlayButton_Click method (if you don’t, start typing its name until it shows up – as shown below). Double-click this option from the list to create a new method.

au13
Click the image to see a larger version.

Step 13

Inside the new PlayButton_Click method add the line _player.Start(); – this will play the sound file when the button is clicked/tapped by the user. You can use this line anywhere in your app to play the sound (not just on a click event).

au14
Click the image to see a larger version.

That’s it! Now go and test your app. Hint: You can also add a button that runs the line of code _player.Stop(); to stop the audio file playing.

au15

Controlling audio with scripts

This tutorial explains how to control the audio in your game using scripts. You can play, stop, pause and resume sound effects and songs in your game when certain events occur by controlling the sound with code. This video explains how to do that and if you scroll down you will find the sample code.

The following sample code is used to control an audio source/slot called “song” that is attached to the same entity that the script is attached to. The filename of this script is playsong.js.

pc.script.create('playsound', function (app) {
    // Creates a new Playsound instance
    var Playsound = function (entity) {
        this.entity = entity;
    };

    Playsound.prototype = {
        // Called once after all resources are loaded and before the first update
        initialize: function () {
        },

        // Called every frame, dt is time in seconds since last update
        update: function (dt) {
            if(app.keyboard.wasPressed(pc.input.KEY_P)){
                this.entity.sound.play('song');
            }
            
            if(app.keyboard.wasPressed(pc.input.KEY_S)){
                this.entity.sound.stop('song');
            }
        }
    };

    return Playsound;
});

The following sample code is used to control an audio source/slot called “song” that is attached to a Sound entity called “mySound“. The script can be attached to any other entity in the game scene. The filename of this script is playsong.js.

pc.script.create('playsound', function (app) {
    // Creates a new Playsound instance
    var Playsound = function (entity) {
        this.entity = entity;
    };

    Playsound.prototype = {
        // Called once after all resources are loaded and before the first update
        initialize: function () {
        },

        // Called every frame, dt is time in seconds since last update
        update: function (dt) {
            // creates variable for audio entity
            var AudioEntity = app.root.findByName('mySound');
            if(app.keyboard.wasPressed(pc.input.KEY_P)){
                AudioEntity.sound.play('song');
            }
            
            if(app.keyboard.wasPressed(pc.input.KEY_S)){
                AudioEntity.sound.stop('song');
            }
        }
    };

    return Playsound;
});

South Of The Border by Audionautix is licensed under a Creative Commons Attribution licence (https://creativecommons.org/licenses/by/4.0/)
Artist: http://audionautix.com/

Adding sound to a game in PlayCanvas

This tutorial explains how to add sound effects and background music to your game in PlayCanvas. You can add sounds that can be heard from anywhere in the game or attach sounds to objects that can only be heard when your character is near them in the game.

You can also add sounds that automatically play and loop in the background and you can also control when sounds play and stop using code. Using code to control sound will be explained in the next tutorial. Watch the video below to see how to add sound to your game.

South Of The Border by Audionautix is licensed under a Creative Commons Attribution licence (https://creativecommons.org/licenses/by/4.0/)
Artist: http://audionautix.com/

Adding sound to your scene

In this tutorial you will learn how add sound to a scene in your game. You can add sounds that play constantly in a scene such as background music and you can also add sounds that only occur every now and then or that occur after an event. Sounds can also be looped or just play once.

There is also 2D sound (heard everywhere in your scene) and 3D sound (heard only when you are in a specified proximity to an object/sound). Sound can be scripted but you can also add sound without any code at all.

Watch the video below or scroll down to read the step-by-step instructions and sample code.

To add audio to your scene, follow these steps:

  1. Make sure there is one (and only one) Audio Listener component in your scene. It should be attached to the character controller’s camera or main camera. Delete or disable any other audio listeners as there can only be one in any scene.
  2. Add an object (eg. empty object, cube, sphere) or use an existing object in your scene to add the sound to.
  3. Select the object and click ‘Add component’ in the Inspector panel.
  4. Add the ‘Audio source’ component to the object.
  5. Find an audio file (eg. MP3, OGG file) and add it to the ‘audio clip’ property on the audio source component in the inspector panel.
  6. To make the sound play throughout the whole scene, enable ‘Play on awake’. You can also check the ‘Loop’ option to make the sound repeat/loop. Play the scene to test your audio.
  7. To use the audio file as 3D audio, drag the ‘Spatial Blend’ slider from 2D to 3D – this means that you will only hear the sound when you are near the object. You can change some of the properties to specify how it fades away and how close to the object the player needs to be to hear the sound.

To script the audio, add this code to the Start() method:

GetComponent<AudioSource> ().Play();

and to stop the audio:

GetComponent<AudioSource> ().Stop ();

You could also add an ‘if’ statement eg. to make the sound play when a key is pressed. For example, you could add this ‘if’ statement to the Update() method.:

if (Input.GetKey(KeyCode.Space)) {
 GetComponent<AudioSource>().Play();
}

Also, you can check if audio is currently playing by using .isPlaying(). Any looping sound or a song can be turned on and off using an if statement that checks if the audio is currently playing – just add something like this to your Update() method.

if (Input.GetKey (KeyCode.Space)) {
 if(GetComponent<AudioSource>().isPlaying == true){
 GetComponent<AudioSource>().Stop ();
 }
 else{
 GetComponent<AudioSource>().Play ();
 }
 }

How to change the audio clip using code?

If you want to change the audio clip on the audio source during the game (maybe after a certain event or when a key is pressed), you will need to add the following line inside the class (outside of all other methods) in your script:

public AudioClip otherClip;

You will then need to stop the current audio clip from playing before you switch to another audio clip and start playing that one. Inside the Update() method (or whichever method you are controlling the audio from), you will need to add the following code. This code may be placed inside an if statement (eg. if x key is pressed):

GetComponent<AudioSource>().Stop ();

Then, after you have added that line of code you can switch the audio clip and start playing the new audio clip using this code:

GetComponent<AudioSource>().clip = otherClip;
GetComponent<AudioSource>().Play ();

Lastly, you will need to go into Unity and drag the audio clip file (eg. MP3, OGG file) onto the ‘otherClip’ property on the script component (for this script) in the Inspector panel.

Adding audio to a webpage

This tutorial explains how to add audio to a webpage using the HTML5 audio tag. Because this tag is new to HTML5, it may not be supported in some older browsers. It is also important to note that some audio file types may not be supported in different browsers.

At the time of writing this tutorial, the following browsers support these file types using the HTML5 audio tag:

  • Chrome: MP3, WAV, OGG
  • Internet Explorer: MP3
  • Firefox: MP3, WAV, OGG
  • Safari: MP3, WAV
  • Opera: MP3, WAV, OGG

Using MP3 files for audio would be the safest bet as it is supported by all the major browsers now. For this tutorial, I will demonstrate using the HTML5 audio tag with an MP3 file. You can get free audio files from a range of sources including the YouTube Audio Library and Freesound.

When you add audio to a page you can specify whether you want to allow the audio to automatically play, loop over, and if you also want to show or hide the audio player controls which will look like this:

audioplayer

The video below shows how you can use the HTML5 audio tag to add an audio file to a webpage. It also shows how to add controls and how to autoplay and loop audio files. Watch the video below and then scroll down to see the sample code.

The sample code below shows how to add an audio file to a webpage. All you need to do is replace the filename/filetypes with whatever you are using. You might also like to remove the autoplay, loop, or control features. Note that all three of these features are enabled in the example below.

<!DOCTYPE html>
<html>
<head>
 <title>Adding audio to a webpage</title>
 <meta charset="utf-8"/>
</head>

<body>
<audio controls autoplay loop>
 <source src="your_audio_file.mp3" type="audio/mpeg"/>
 Your browser does not support the HTML5 audio tag. Consider updating to a newer browser.
</audio>
</body>

</html>

This tutorial video includes a portion of free music from the YouTube Audio Library. Music from the audio library can be used in your videos by you as long as you do not make it available, distribute or perform the music separately from your videos into which you have incorporated the music files, and as long as the music is not used in an illegal manner or in connection with any illegal content. Always read the terms and conditions.