Skip to content

Latest commit

 

History

History
46 lines (35 loc) · 1.65 KB

Play-sound-once-or-looped.md

File metadata and controls

46 lines (35 loc) · 1.65 KB

Play a sound once or looped

Plays a sound, either once or continuously.

using System;
using System.Threading.Tasks;
using Windows.Storage;
using Windows.UI.Xaml.Controls;

public static async Task PlayAudioAsync(IStorageFile mediaFile, bool looping = false) 
{
    var stream = await mediaFile.OpenAsync(FileAccessMode.Read).AsTask();
    var mediaControl = new MediaElement() { IsLooping = looping };
    mediaControl.SetSource(stream, mediaFile.ContentType);
    mediaControl.Play();
}

The sound is passed in as an IStorageFile. You can load your sound file as a StorageFile object by using a method like GetFileFromApplicationUriAsync.

There are several ways to play sound in a Universal Windows Platform (UWP) app. This method uses the MediaElement class. The AudioGraph class provides additional control over playing sound.

Usage

var soundFile = await StorageFile.GetFileFromApplicationUriAsync(
    new Uri("ms-appx:///Assets/test.mp3"));
await PlayAudioAsync(soundFile);

See also

IStorageFile interface
StorageFile class
StorageFile.GetFileFromApplicationUriAsync method
MediaElement class
AudioGraph class