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:
Open Xamarin and click File > New Solution. Then select iOS App and SingleView App as the project template. Click Next.
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.
When the solution opens, right-click on the project folder. Select Add > New Folder.
Give the new folder the name Sounds.
Right-click on the new Sounds folder and select Add > Add files from folder.
Navigate to the folder which contains the audio file(s) you wish to use in your app. Click Open.
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.
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.
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).
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.
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.
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.
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
That’s it! Now go and test the app!