wp7appdevelopment

Adventures in Windows Phone app development

Monthly Archives: October 2012

How to Make a Windows Phone 7 Vibrate (C#)

Vibrate your phone?

There are many reasons you might want to programmatically vibrate the phone during apps or games.  You might want to alert the user to an error condition, and emphasize that a button has been clicked.

The Windows Phone 7 SDK makes it easy for developers to control the vibrate function easily, using the VibrateController class. The VibrateController class is defined in the namespace Microsoft.Devices.

The following example shows how to vibrate the phone using C#:


using Microsoft.Devices;

VibrateController vibrate = VibrateController.Default;
vibrate.Start(TimeSpan.FromMilliseconds(200));

That’s all that you need to do! You can change the vibrate duration — this example uses 200 milliseconds.
Of course, common-sense best practices: don’t overdo the use of vibration, and give the user the option to disable.

References

VibrateController class documentation

Windows 8 (Win8 Metro) C#/Silverlight: Playing Sound in Apps

This example shows how to play sounds in a Windows 8 app developed using C#/Silverlight.

Updated: See Simpler Example section below.

Key steps are:

  • Create a MediaElement object
  • Read in the sound file to a stream
  • Set the source of your MediaElement object using the stream
  • Call the MediaElement.Play() method to play the sound
MediaElement _mySound = new MediaElement();
Windows.Storage.StorageFolder folder = await Package.Current.InstalledLocation.GetFolderAsync("Sounds");
Windows.Storage.StorageFile file = await folder.GetFileAsync("sound.wav");
var stream = await file.OpenmReadAsync();
mySound.SetSource(stream, file.ContentType);

mySound.Play();

Example Implementation

The following example assumes the sound files are stored in a folder named Sounds. The InitializeSound() method is called once, to read in the sound files and initialize the MediaElements. After initialization, the PlaySound() method can be called to play the sound. PlaySound() takes one argument, which is the MediaElement (sound) to be played. This example also assumes a global variable (bool _useSound) that is used to conditionally play the sound in the game.

One important note: You must set the MediaElement AutoPlay property to false before setting the Source property. This prevents the sound from playing during initialization.

        private MediaElement _cardSound = new MediaElement();
        private MediaElement _dingSound = new MediaElement();

        private void InitializeSound()
        {
            LoadSound("CardFlip.wav",  _cardSound);
            LoadSound("success.wav",  _dingSound);

        }

        private async void LoadSound(string SoundFilePath, MediaElement SoundElement)
        {
            // all sounds are stored in the Sounds folder
            try
            {
                Windows.Storage.StorageFolder folder = await Package.Current.InstalledLocation.GetFolderAsync("Sounds");
                Windows.Storage.StorageFile file = await folder.GetFileAsync(SoundFilePath);
                var stream = await file.OpenReadAsync();
                SoundElement.AutoPlay = false;
                SoundElement.SetSource(stream, file.ContentType);
            }
            catch
            {
                System.Diagnostics.Debug.WriteLine("Problem opening sound file: " + SoundFilePath);
            }
        }

        private void PlaySound(MediaElement SoundElement)
        {

            // only play sounds if the user has 'play sounds' enabled
            if (_useSound)
            {
                try
                {
                    SoundElement.Play();
                }
                catch
                {
                    System.Diagnostics.Debug.WriteLine("Problem playing sound: " + SoundElement.ToString());
                }
            }
        }

Simpler Example

Here’s a simpler way to play a sound. This works if you won’t be changing the source of the MediaElement:

  1. Add a MediaElement to your visual tree (e.g., LayoutRoot) in your XAML. 
  2. Specify the source for the MediaElement in the XAML.
  3. Call MediaElement.Play() to play the sound.

But, if you want to be able to programmatically change the source in your C# code behind, you’ll need to wait for the new media file to load before it will play. If you just change the source and then immediately call Play(), the media file won’t be loaded and it therefore won’t play.

  1. Register a handler for MediaSource.MediaOpened events.
  2. Set MediaElement.Source in your xaml.cs file.
  3. In your MediaOpened handler, call Play().

Here’s an example. Create a MediaElement object in your XAML:

 <MediaElement x:Name="sound" AutoPlay="False" />

In an initializer function (constructor, OnNavigatedTo, etc.) in your xaml.cs,  register the handler for MediaOpened events for our MediaElement:

sound.MediaOpened += sound_MediaOpened;

Add the code that changes the source file. (Note: I created a Sounds folder in my project, so my pathnames look like “ms-appx:///Sounds/mysoundfile.wma”)

        private void PlaySoundButton_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                sound.Source = new Uri("insert new file path here", UriKind.Absolute);

            }
            catch { }
        }

Add the code for the sound_MediaOpened() handler:

void sound_MediaOpened(object sender, RoutedEventArgs e)
{
    sound.Play();
}

When your code is called to change the source file, the system will go and open the specified file. Assuming it’s able to be opened with no errors, the sound_MediaOpened() method will then be called. When we call sound.Play(), our new sound file will play.

Windows 8 (Win8 Metro) C#/Silverlight: Programmatically Setting Image Source

Specifying an Image.Source

If you are developing a Windows 8 (WinRT) app using C#/XAML, you can set the source for images either using XAML or programmatically in your C# code-behind file.

Using XAML

It’s trivial to set an image’s source in the XAML using Visual Studio Express 2012. Assume you have the folder “Images” in your current project, and in this folder you have an image file named “myPic.png”. The following XAML declaration sets the Image.Source property:

  <Image Height="100" Width="100" Source="Images/myPic.png" />

Using C#

But what if you need to programmatically set the source property? Turns out that’s trivial, too — assuming you know the correct path naming.  Assume the same scenario — an “Images” folder that contains the image file “myPic.png.”


Image myImage = new Image() { Width="100", Height="100"};
myImage.Source = new BitmapImage(new Uri("ms-appx:///Images/myPic.png", UriKind.Absolute));

This code creates a new absolute URI that specifies the image file location, and then uses this Uri to create a new BitmapImage. Two important details to getting this to work:

  • You must use an Absolute pathname in the URI; relative pathnames are not supported
  • To specify the absolute pathname for resources in your project, use: “ms-appx:///folder_name/file_name

Simple, once you know the correct path to use. I had trouble finding clear documentation on this — hope this saves you some time!