Tag Archives: smart

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!

Creating your first iOS app

This tutorial will show you how to create a Temperature Converter app for iOS devices using Xamarin. We made the same app for Android in a previous tutorial and now we are going to make it for iOS devices. The app will look like this…

iosapp

Although we will be using Xamarin for designing and coding the app, you will still need to have XCode installed on your Mac device (click here for detailed installation instructions).

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

Video

Step 1

To get started, open Xamarin and begin a New Solution.

ios1

Step 2

Select App under iOS and then select Single View App (C#). Click on Next to continue.

ios2

Step 3 

Give your app a name. In this case, it will be called TempConverter. You also need to select a minimum iOS version you want to support. In this case, the target version is iOS 9.1. Make sure the target version is either an older or same version of iOS that you will be using to run the app on. Click Next to continue.

ios3

Step 4

Now just confirm the project and solution name (making sure it is not the same name as a solution that already exists in your projects folder) as well as the project folder location and click Create.

ios4

Step 5

Once the new solution has loaded, Xamarin will automatically open a file called AppDelegate.cs. Don’t worry about this file for now as we won’t really be changing anything there. The two files that we will be working with are the Main.storyboard file (for adding the buttons, text labels, and text boxes) and ViewController.cs (for coding the functionality).

ios5

Double-click the Main.storyboard file to open it. It may take a minute to load. The storyboard is where you will add your user interface elements such as buttons, text boxes and text labels. Choose the iPhone device that you want to use as the preview for your storyboard eg. iPhone 6.

ios6

Step 6

In the Toolbox panel (use the search box to find and add the Toolbox to your layout if you don’t see it there), scroll down until you see Label (you can also search in the Toolbox for the Label element.

Drag a Label element on to the phone screen where you would like to place it.

ios7

Step 7

Change the Text value in the Properties panel (on the Widgets tab) to ‘Enter temperature in degrees:’.

ios8

Step 8

Drag the edges of the Label element to resize it so that you can see all of the text.

ios9

You can also change the colour of the text, the font and alignment (eg. align to center) from the Properties panel.

ios10

Step 9

Drag a Text Field element from the Toolbox on to the screen under the text label. Change its Placeholder text to ‘Temperature in degrees’. Resize the Text Field and center-align the text.

ios11

Step 10

Drag two Button elements on to the screen and resize them to fit their text. Change the first button’s text to ‘Convert to Celsius’ and the second button’s text to ‘Convert to Fahrenheit’.

ios12

Step 11

The last element to add is the text label which will display the result of the temperature conversion. Drag a Label element on to the screen and change its default Text to 0, change its Colour and Font size/style. You can also change the Alignment to center.

ios13

Step 12

Now we need to name each of the screen elements so that they can be accessed by the code. Firstly, click on the temperature text field and change its Name to tempTextField.

ios14

Step 13

Now give the ‘Convert to Celsius’ button the Name cButton.

ios15

Also set the Name of the ‘Convert to Fahrenheit’ button to fButton.

ios16

Step 14

Lastly, click on the text label which will display the conversion result and change its Name to resultLabel. Now is a good time to save the Main.storyboard file (Click File > Save).

ios17

Step 15

Now its time to do some coding. Open the ViewController.cs file. In this file, click inside the ViewDidLoad method and add the code highlighted below. This code will add a button touch event that will occur when the user touches to Convert to Celsius button. When we create the cButton.TouchUpInside event it will also automatically create a new method CButton_TouchUpInside which will contain the code that will convert a temperature to Celsius.

ios18

Step 16

We now need to also create a button touch event for the Convert to Fahrenheit button and a method that will contain its code.

ios19

Step 17

Now let’s add the code for the FButton_TouchUpInside method first. This method will be called when the Convert to Fahrenheit button is pressed by the user. Add the highlighted code below. Firstly, a float variable called temp is created to store the temperature value that the user enters into the text field as a float value. Then a variable called fResult will convert the temperature from Celsius to Fahrenheit and store the result as a float value. Lastly, the text on the resultLabel element will display the result and the text ‘degrees Fahrenheit’ at the end of the sentence eg. ’68 degrees Fahrenheit’.

ios20

Note: You may need to resize the fResult label element in the Main.storyboard file so that it can fit the result and text.

Step 18

We can now add the code for the Convert to CButton_TouchUpInside method to run the conversion when the Convert to Celsius button is pressed. Add the highlighted code to this method shown below. Then save your code (File > Save).

ios21

Step 19

Now go back to the Main.storyboard file and select the Text Field element. In the Properties panel and on the Widget tab, scroll down and change the Keyboard Type to Decimal Pad so that numbers with decimal place can be typed in and the most suitable keypad is displayed. Save the file.

ios22

Step 20

At this point, the app will work and will allow the user to type in a temperature (as a whole or decimal number) and convert it to either Celsius or Fahrenheit. However, after the user has typed in a number they should be able to hid the keyboard if it is no longer needed.

Before testing the app we will add a little piece of code that will allow the keypad to be dismissed by the user when it is no longer needed. To do this, go back to the ViewController.cs file and start typing the highlighted line of code (where it is shown below). As you start typing override touchesBegan you should see an auto-complete suggestion called TouchesBegan(NSSet touches, UIEvent evt). Press the Enter/Return key on your keyboard to auto-complete the line of code. This will create a new override method called TouchesBegan. Inside this method we will add some code to dismiss the keyboard.

ios23
As you start typing override touchesBegan you should see an auto-complete suggestion called TouchesBegan(NSSet touches, UIEvent evt). Press the Enter/Return key on your keyboard to auto-complete the line of code.

Add the following code inside the new override method called TouchesBegan to allow the keyboard to be dismissed when typing has been completed by the user. Then save the file.

ios24

Finishing up

All of the coding is done. Congratulations – you have made your first iOS app using Xamarin and the C# programming language! Remember to save your files.Now just select a type of iPhone model you would like to test this app on and click on the Build button to start testing/emulating the app.

ios25

And this is what the completed app should look like…

ios26

What next?

Test your app thoroughly. Are there any problems with your app? Does it crash under some circumstances? Is there any way it could be improved. Jump into the next tutorial to see how this app can be improved.

Sample code

You can download the sample code for the ViewController.cs file here:

using System;

using UIKit;

namespace TempConverter
{
  public partial class ViewController : UIViewController
  {
    public ViewController (IntPtr handle) : base (handle)
    {
    }

    public override void ViewDidLoad ()
    {
      base.ViewDidLoad ();
      // Perform any additional setup after loading the view, typically from a nib.e

      cButton.TouchUpInside+= CButton_TouchUpInside;

      fButton.TouchUpInside+= FButton_TouchUpInside;

    }

    void FButton_TouchUpInside (object sender, EventArgs e)
    {
      float temp = float.Parse(tempTextField.Text);
      float fResult = temp * 1.8f + 32f;
      resultLabel.Text = fResult.ToString () + " degrees Fahrenheit";
    }

    void CButton_TouchUpInside (object sender, EventArgs e)
    {
      float temp = float.Parse (tempTextField.Text);
      float cResult = (temp - 32f) / 1.8f;
      resultLabel.Text = cResult.ToString () + " degrees Celsius";
    }

    public override void DidReceiveMemoryWarning ()
    {
      base.DidReceiveMemoryWarning ();
      // Release any cached data, images, etc that aren't in use.
    }
      
    public override void TouchesBegan (Foundation.NSSet touches, UIEvent evt)
    {
      base.TouchesBegan (touches, evt);

      this.View.EndEditing (true);
    }
  }
}

Making a Cookie Clicker game for Android

For our second Android app project, we will create the most pointless but addictive game in the world…a cookie clicker! A basic version of it will look like the image shown below, but you can extend this game as much as you like. You will also learn how to add image buttons to your app screens.

cc1

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

Video

Step 1

You will need to create a new Android App solution in Xamarin called CookieClicker. Click on New Solution (or File > New Solution) to get started.

cc2

Step 2

Choose Android App as the type of new solution and then click Next.

cc3

Step 3

Set the App Name to CookieClicker (one word – no spaced). Choose Modern Development as the Targeted Platform using the default theme and click on Next.

cc4

Step 4

Keep the project and solution names as CookieClicker, select a project location to store your files in and click on Create.

cc5

Step 5

Open the MainActivity.cs file (if it does not automatically open) and delete the lines of code highlighted below. These lines of code won’t be needed for this project.

cc6
Click to see larger version of this image.

Step 6

Now open the Main.axml file located in the Resources > layout folder.

cc7

Step 7

Click on the button that says “Hello World, Click Me!”. We won’t need this button so it can be deleted. Either click on it and press the Delete key on your keyboard, or right-click the button and select Delete.

cc8

Step 8

From the Toolbox (if you don’t see it, you can search for the Toolbox from the search bar), scroll down under Images & Media and drag an ImageButton element on to the phone screen.

cc9

Step 9

Now you will need to download a cookie image to your computer (preferably a PNG image file with a transparent background). A free public-domain image has been provided below. Click on the image to open the full-size version and then save the image to a folder on your computer and name it cookie.png.

Click to open the full-size image. Image from: https://pixabay.com/en/chocolate-chip-cookies-dessert-304801/ (CC0 Public Domain - free for commercial use, no attribution required)
Click to open the full-size image. Image from: https://pixabay.com/en/chocolate-chip-cookies-dessert-304801/ (CC0 Public Domain – free for commercial use, no attribution required)

Step 10

Select the ‘drawable’ folder inside the Resources folder and click on the small cog icon. Then select Add > Add Files from Folder.

cc10

Step 11

Select the folder that contains the cookie image file and click on Open.

cc11

Step 12

Select the cookie.png file (or whatever yours is called) and make sure the checkbox is checked. Then click on OK.

cc12

Step 13

Make sure you select Copy the file to the directory and then click on OK.

cc13

Step 14

Now you should see cookie.png in the drawable folder.

cc14

Step 15

Click on the ImageButton element on the phone screen and change the Src property to @drawable/cookie (you do not need to include the .png file extension).

cc15

Step 16

Now we need to make sure the image fits properly on the screen. Click on the drop-down arrow next to the Scale Type property and change it to fitCenter.

cc16a

You can then also click on the ImageButton and drag the little circle up to change the height of the image. You can also change the width of the image this way. Alternatively, go to the Layout tab on the Properties panel and change the width and height values there eg. 435dp for the height. Note: sizes of elements are measured using the ‘dp’ unit on Android.

cc16b

cc16c

If you go to the Source tab, your code for the Main.axml file might look like the code shown below. However, your code could be a little different so don’t change the code here unless you are sure you know what you are doing.

cc16d

Step 17

In the Designer view, drag a Text (Large) element on to the phone screen under the ImageButton. This will be used to display the number of clicks.cc17

Step 18

From the Widget tab on the Properties panel, change the Text value from Large Text to 0 clicks. At the same time, change its Id from @+id/textView1 to @+id/cookieTextView . You can also change the Gravity value to center so the text is centered.

cc18

Step 19

Click on the ImageButton element (the cookie) and change its Id from @+id/imageButton1 to @+id/cookieImageButton – now you need to save the Main.axml file.

cc19

Step 20

Now we can add the code! Open the MainActivity.cs file and create an integer variables called clicks that is given an initial integer value of 0. This variable will be created inside the MainActivity class, as highlighted below.

cc20

Step 21

We also need to define the ImageButton element and the TextView element in the code. This is highlighted in the lines below. Make sure to use the correct names for each element.

cc21

Step 22

Inside the OnCreate method (under the SetContentView (Resource.Layout.Main); line), we need to now setup the ImageButton and TextView element.

cc22

Step 23

The next thing you need to do is create a click event for the cookie ImageButton by adding the line cookieImageButton.Click+= CookieImageButton_Click; – this will create a new method called CookieImageButton_Click which will contain the code that will increase the number of clicks and display the number of clicks each time the ImageButton is tapped.

cc23

Step 24 

Inside the CookieImageButton_Click method, add the following two highlighted lines of code. The clicks++; line will increase the clicks variable by 1 each time the button is tapped, and the next line of code is responsible for converting the clicks variable value to a string and displaying the clicks variable’s value on the screen as well as the text “clicks!” at the end eg. 25 clicks!

cc24a

Now save your work. All of the coding is done! Now you could extend this app by adding extra buttons to purchase items when a certain number of cookies are clicked (using if statements) or increase the number of cookies by a different amount. You could add extra text labels or buttons too. However, let’s test that this app works properly first. Click on the Build button after selecting a virtual device to run the app on (if you don’t know how to do this, refer to the previous tutorial – Creating your first Android app with Xamarin).

cc25a

cc25b

Here is the source code for the MainActivity.cs file:

using Android.App;
using Android.Widget;
using Android.OS;

namespace CookieClicker
{
  [Activity (Label = "CookieClicker", MainLauncher = true, Icon = "@midmap-hdpi/icon")]
  public class MainActivity : Activity
  {
    int clicks = 0;

    ImageButton cookieImageButton;
    TextView cookieTextView;

    protected override void OnCreate (Bundle savedInstanceState)
    {
      base.OnCreate (savedInstanceState);

      // Set our view from the "main" layout resource
      SetContentView (Resource.Layout.Main);

      cookieImageButton = FindViewById<ImageButton> (CookieClicker.Resource.Id.cookieImageButton);
      cookieTextView = FindViewById<TextView> (CookieClicker.Resource.Id.cookieTextView);

      cookieImageButton.Click+= CookieImageButton_Click;

    }

    void CookieImageButton_Click (object sender, System.EventArgs e)
    {
      clicks++;
      cookieTextView.Text = clicks.ToString () + " clicks!";
    }
  }
}