Search icon CANCEL
Subscription
0
Cart icon
Your Cart (0 item)
Close icon
You have no products in your basket yet
Arrow left icon
Explore Products
Best Sellers
New Releases
Books
Videos
Audiobooks
Learning Hub
Conferences
Free Learning
Arrow right icon

Using Resources

Save for later
  • 6 min read
  • 06 Oct 2015

article-image

In this article written by Mathieu Nayrolles, author of the book Xamarin Studio for Android Programming: A C# Cookbook, wants us to learn of how to play sound and how to play a movie by using an user-interactive—press on button in a programmative way.

(For more resources related to this topic, see here.)

Playing sound

There are an infinite number of occasions in which you want your applications to play sound. In this section, we will learn how to play a song from our application in a user-interactive—press on a button—or programmative way.

Getting ready

For using this you need to create a project on your own:

How to do it…

  1. Add the following using parameter to your MainActivity.cs file.
    using Android.Media;

  2. Create a class variable named _myPlayer of the MediaPlayer class:
       MediaPlayer _myPlayer;

  3. Create a subfolder named raw under Resources.
  4. Place the sound you wish to play inside the newly created folder.
  5. We will use the Mario theme, free of rights for non-commercial use, downloaded from http://mp3skull.com.
  6. Add the following lines at the end of the OnCreate() method of your MainActivity.
    _myPlayer = MediaPlayer.Create (this, Resource.Raw.mario);
    
     
    
    Button button = FindViewById<Button> (Resource.Id.myButton);
    
     
    
    button.Click += delegate {
    
       _myPlayer.Start();
    
    };

In the preceding code sample, the first line creates an instance of the MediaPlayer using the this statement as Context and Resource.Raw.mario as the file to play with this MediaPlayer. The rest of the code is trivial, we just acquired a reference to the button and create a behavior for the OnClick() event of the button. In this event, we call the Start() method of the _myPlayer() variable.

Run your application and press on the button as shown on the following screenshot:

using-resources-img-0

You should hear the Mario theme playing right after you pressed the button, even if you are running the application on the emulator.

How it works...

Playing sound (and video) is an activity handled by the Media Player class of the Android platform. This class involves some serious implementations and a multitude of states in the same way as activities. However, as an Android Applications Developer and not as an Android Platform Developer we only require a little background on this.

The Android multimedia framework includes—thought the Media Player class—a support for playing a very large variety of media such MP3 from the filesystem or from the Internet. Also, you can only play a song on the current sound device which could be the phone speakers, headset or even a Bluetooth enabled speaker. In other words, even if there are many sound outputs available on the phone, the current default settled by the user is the one where your sound will be played. Finally, you cannot play a sound during a call.

There's more...

Playing sound which is not stored locally

Obviously, you may want to play sounds that are not stored locally—in the raw folder—but anywhere else on the phone, like SDcard or so. To do it, you have to use the following code sample:

Uri myUri = new Uri ("uriString");

_myPlayer = new MediaPlayer();

_myPlayer.SetAudioStreamType (AudioManager.UseDefaultStreamType);

_myPlayer.SetDataSource(myUri);

_myPlayer.Prepare();

The first line defines a Uri for the targeting file to play. The three following lines set the StreamType, the Uri prepares the MediaPlayer. The Prepare() is a method which prepares the player for playback in a synchrone manner. Meaning that this instruction blocks the program until the player is ready to play, until the player has loaded the file. You could also call the PrepareAsync() which returns immediately and performs the loading in an asynchronous way.

Playing online sound

Using a code very similar to the one required to play sounds stored somewhere on the phone, we could play sound from the Internet.

Basically, we just have to replace the Uri parameter by some HTTP address just like the following:

Unlock access to the largest independent learning library in Tech for FREE!
Get unlimited access to 7500+ expert-authored eBooks and video courses covering every tech area you can think of.
Renews at €18.99/month. Cancel anytime

String url = "http://myWebsite/mario.mp3";

_myPlayer = new MediaPlayer();

_myPlayer.SetAudioStreamType (AudioManager.UseDefaultStreamType);

_myPlayer.SetDataSource(url);

_myPlayer.Prepare();

Also, you must request the permission to access the Internet with your application. This is done in the manifest by adding an <uses-permission> tag for your application as shown by the following code sample:

<application android_icon="@drawable/Icon" android_label="Splash">

<uses-permission android_name="android.permission.INTERNET" />

</application>

See Also

  • See also the next recipe for playing video.

Playing a movie

As a final recipe in this article, we will see how to play a movie with your Android application. Playing video, unlike playing audio, involves some special views for displaying it to the users.

Getting ready

For the last time, we will reuse the same project, and more specifically, we will play a Mario video under the button for playing the Mario theme seen in the previous recipe.

How to do it...

  1. Add the following code to your Main.axml under Layout file:
    <VideoView android_id="@+id/myVideoView"
    
    android_layout_width="fill_parent"
    
    android_layout_height="fill_parent">
    
    </VideoView>

  2. As a result, the content of your Main.axml file should look like the following screenshot:

    using-resources-img-1

  3. Add the following code to the MainActivity.cs file in the OnCreate() method:
    var videoView = FindViewById<VideoView> (Resource.Id.SampleVideoView);
    
    var uri = Android.Net.Uri.Parse ("url of your video");
    
    videoView.SetVideoURI (uri);

  4. Finally, invoke the videoView.Start() method.

Note that playing Internet based video, even short one, will take a very long time as the video need to be fully loaded while using this technique.

How it works...

Playing video should involve some special view to display it to users. This special view is named the VideoView tag and should be used as same as simple TextView tag.

<VideoView android_id="@+id/myVideoView"

android_layout_width="fill_parent"

android_layout_height="fill_parent">

</VideoView>

As you can see in the preceding code sample, you can apply the same parameters to VideoView tag as TextView tag such as layout based options.

The VideoView tag, like the MediaPlayer for audio, have a method to set the video URI named SetVideoURI and another one to start the video named Start();.

Summary

In this article, we've learned how to play a sound clip as well as video on the Android application which we've developed.

Resources for Article:


Further resources on this subject: