(予め)本記事はプレビュー版の環境に基づいて書かれています。
Windows 1o Desctop Build 10240
Windows 1o Mobile Build 10166
Visual Studio 2015 RC
製品版では内容と異なる可能性もあります。
紹介したプロジェクトは以下から実行可能です。
UWPアプリのサンプル(GitHub)
音楽の再生といえばMediaElementですが、今回はAudioGraphを利用します。
AudioGraphを用いると単なる音楽の再生だけでなく、加工などの高度な処理が可能になります。
まずAudioGraphを作成します。
// Create an AudioGraph with default settings
AudioGraphSettings settings = new AudioGraphSettings(AudioRenderCategory.Media);
CreateAudioGraphResult result = await AudioGraph.CreateAsync(settings);
if (result.Status != AudioGraphCreationStatus.Success)
{
// Cannot create graph
rootPage.NotifyUser(String.Format("AudioGraph Creation Error because {0}", result.Status.ToString()), NotifyType.ErrorMessage);
return;
}
graph = result.Graph;
// Create a device output node
CreateAudioDeviceOutputNodeResult deviceOutputNodeResult = await graph.CreateDeviceOutputNodeAsync();
ファイルをAudioGraphにセットします。
FileOpenPicker filePicker = new FileOpenPicker();
filePicker.SuggestedStartLocation = PickerLocationId.MusicLibrary;
filePicker.FileTypeFilter.Add(".mp3");
filePicker.FileTypeFilter.Add(".wav");
filePicker.FileTypeFilter.Add(".wma");
filePicker.FileTypeFilter.Add(".m4a");
filePicker.ViewMode = PickerViewMode.Thumbnail;
StorageFile file = await filePicker.PickSingleFileAsync();
// File can be null if cancel is hit in the file picker
if(file == null)
{
return;
}
CreateAudioFileInputNodeResult fileInputResult = await graph.CreateFileInputNodeAsync(file);
if (AudioFileNodeCreationStatus.Success != fileInputResult.Status)
{
// Cannot read input file
rootPage.NotifyUser(String.Format("Cannot read input file because {0}", fileInputResult.Status.ToString()), NotifyType.ErrorMessage);
return;
}
fileInput = fileInputResult.FileInputNode;
fileInput.AddOutgoingConnection(deviceOutput);
fileButton.Background = new SolidColorBrush(Colors.Green);
// Trim the file: set the start time to 3 seconds from the beginning
// fileInput.EndTime can be used to trim from the end of file
fileInput.StartTime = TimeSpan.FromSeconds(3);
で、再生します。
graph.Start();
これ以外に、再生速度を変えたり、シーク、ミックスなど色々参考になるコードがありますので、ぜひご確認を。
Windows 8.1時代のMediaElementを用いた再生ももちろん可能です。
FileOpenPicker filePicker = new FileOpenPicker();
filePicker.SuggestedStartLocation = PickerLocationId.MusicLibrary;
filePicker.FileTypeFilter.Add(".mp3");
filePicker.FileTypeFilter.Add(".wav");
filePicker.FileTypeFilter.Add(".wma");
filePicker.FileTypeFilter.Add(".m4a");
filePicker.ViewMode = PickerViewMode.Thumbnail;
StorageFile file = await filePicker.PickSingleFileAsync();
// File can be null if cancel is hit in the file picker
if (file == null)
{
return;
}
var stream = await file.OpenAsync(Windows.Storage.FileAccessMode.Read);
this.me.SetSource(stream, file.ContentType);
this.me.Play();
Please give us your valuable comment