与众不同 windows phone (40) - 8.0 媒体: 音乐中心的新增功能, 图片中心的新增功能, 后台音乐播放的新增功能

简介: 原文:与众不同 windows phone (40) - 8.0 媒体: 音乐中心的新增功能, 图片中心的新增功能, 后台音乐播放的新增功能[源码下载] 与众不同 windows phone (40) - 8.
原文: 与众不同 windows phone (40) - 8.0 媒体: 音乐中心的新增功能, 图片中心的新增功能, 后台音乐播放的新增功能

[源码下载]


与众不同 windows phone (40) - 8.0 媒体: 音乐中心的新增功能, 图片中心的新增功能, 后台音乐播放的新增功能



作者:webabcd


介绍
与众不同 windows phone 8.0 之 媒体

  • 添加音乐到音乐中心,从音乐中心删除音乐
  • 与图片中心相关的新增功能
  • BackgroundAudioPlayer 的新增功能



示例
1、演示如何添加音乐到音乐中心,以及如何从音乐中心删除音乐
MusicMediaLibrary/MusicMediaLibrary.xaml

<phone:PhoneApplicationPage
    x:Class="Demo.Media.MusicMediaLibrary"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:phone="clr-namespace:Microsoft.Phone.Controls;assembly=Microsoft.Phone"
    xmlns:shell="clr-namespace:Microsoft.Phone.Shell;assembly=Microsoft.Phone"
    xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
    xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
    FontFamily="{StaticResource PhoneFontFamilyNormal}"
    FontSize="{StaticResource PhoneFontSizeNormal}"
    Foreground="{StaticResource PhoneForegroundBrush}"
    SupportedOrientations="Portrait" Orientation="Portrait"
    mc:Ignorable="d"
    shell:SystemTray.IsVisible="True">

    <Grid Background="Transparent">
        <StackPanel Orientation="Vertical">

            <Button x:Name="btnAdd" Content="添加音乐到音乐中心" Click="btnAdd_Click" />

            <Button x:Name="btnDelete" Content="从音乐中心删除音乐" Click="btnDelete_Click" />

        </StackPanel>
    </Grid>

</phone:PhoneApplicationPage>

MusicMediaLibrary/MusicMediaLibrary.xaml.cs

/*
 * 演示如何添加音乐到音乐中心,以及如何从音乐中心删除音乐
 * 
 * 
 * 在 wp8 中新增了 Microsoft.Xna.Framework.Media.PhoneExtensions.MediaLibraryExtensions,其扩展了 MediaLibrary 类
 *     MediaLibrary.SaveSong(Uri filename, SongMetadata songMetadata, SaveSongOperation operation) - 保存音乐到音乐中心,返回 Song 对象
 *         Uri filename - 需要添加到音乐中心的音乐文件,必须在 IsolatedStorage 下
 *         SongMetadata songMetadata - 元数据
 *         SaveSongOperation operation - CopyToLibrary 拷贝音乐文件;MoveToLibrary 移动音乐文件
 *     MediaLibrary.Delete(Song song) - 根据 Song 对象从音乐中心删除数据
 * 
 * 
 * 注:
 * 1、需要在 manifest 中增加配置 <Capability Name="ID_CAP_MEDIALIB_AUDIO" />
 * 2、音乐文件只支持mp3和wma,且必须在 IsolatedStorage 下
 * 3、音乐的封面文件只支持jpg,且必须在 IsolatedStorage 下
 * 
 * 
 * 另:
 * 1、播放音乐或视频的话,需要在 manifest 中增加配置 <Capability Name="ID_CAP_MEDIALIB_PLAYBACK" />
 * 2、除了用 MediaElement 播放音乐外,还可以用 MediaPlayer(xna) 播放,参见:http://www.cnblogs.com/webabcd/archive/2011/07/11/2102713.html
 */

using System;
using System.Collections.Generic;
using System.Windows;
using Microsoft.Phone.Controls;
using Microsoft.Xna.Framework.Media;
using Microsoft.Xna.Framework.Media.PhoneExtensions;
using System.IO.IsolatedStorage;
using System.IO;
using Windows.Storage.Streams;
using Windows.Storage;
using System.Threading.Tasks;

namespace Demo.Media
{
    public partial class MusicMediaLibrary : PhoneApplicationPage
    {
        private Random _random = new Random();

        public MusicMediaLibrary()
        {
            InitializeComponent();
        }

        private async void btnAdd_Click(object sender, RoutedEventArgs e)
        {
            // 将相关文件复制到 ApplicationData 的 Local 目录下
            await CopyFileToApplicationData(new Uri("ms-appx:///Assets/Demo.mp3", UriKind.Absolute), "Demo.mp3");
            await CopyFileToApplicationData(new Uri("ms-appx:///Assets/Son.jpg", UriKind.Absolute), "Son.jpg");

            // 将相关文件复制到 IsolatedStorage 的根目录下
            // CopyFileToIsolatedStorage(new Uri("Assets/Demo.mp3", UriKind.Relative), "Demo.mp3");
            // CopyFileToIsolatedStorage(new Uri("Assets/Son.jpg", UriKind.Relative), "Son.jpg");

            // 需要添加到音乐中心的音乐文件仅支持mp3和wma,且必须在 ApplicationData 下,以下格式会先在 Local 目录下找,找不到再到 Local/IsolatedStorage 目录下找
            Uri musicUri = new Uri("Demo.mp3", UriKind.Relative);
            // 需要添加到音乐中心的音乐封面文件仅支持jpg,且必须在 ApplicationData 下,以下格式会先在 Local 目录下找,找不到再到 Local/IsolatedStorage 目录下找
            Uri picUri = new Uri("Son.jpg", UriKind.Relative);

            // 构造 SongMetadata 对象
            // 如果按以下内容设置 SongMetadata 对象,则音乐文件在音乐中心的保存路径为:webabcd/webabcd album/music xxxx.mp3
            SongMetadata sm = new SongMetadata();
            sm.AlbumName = "webabcd album";
            sm.ArtistName = "webabcd";
            sm.GenreName = "rock";
            sm.Name = "music " + _random.Next(1000, 10000).ToString();
            sm.ArtistBackgroundUri = picUri;
            sm.AlbumArtUri = picUri;
            sm.AlbumArtistBackgroundUri = picUri;

            MediaLibrary library = new MediaLibrary();

            try
            {
                // 添加音乐文件到音乐中心
                Song song = library.SaveSong(musicUri, sm, SaveSongOperation.CopyToLibrary);
            }
            catch (Exception ex)
            {
                // 如果文件已存在,则会抛出 System.InvalidOperationException 异常
                MessageBox.Show(ex.Message);
            }
        }

        private void btnDelete_Click(object sender, RoutedEventArgs e)
        {
            /*
             * MediaLibrary - 媒体库
             *     Songs - 返回音乐中心的 SongCollection
             *     Albums - 返回音乐中心的 AlbumCollection
             *     Artists - 返回音乐中心的 ArtistCollection
             *     Genres - 返回音乐中心的 GenreCollection
             *     Playlists - 返回音乐中心的 Playlists
             */

            MediaLibrary library = new MediaLibrary();

            // 通过 MediaLibrary 遍历音乐中心中的音乐文件
            foreach (Song song in library.Songs)
            {
                // 从音乐中心删除音乐文件
                if (song.Artist.Name == "webabcd")
                    library.Delete(song);
            }
        }


        // 将文件从 Package 复制到 IsolatedStorage 的根目录下
        private void CopyFileToIsolatedStorage(Uri sourceUri, string targetFileName)
        {
            IsolatedStorageFile isf = IsolatedStorageFile.GetUserStoreForApplication();
            using (Stream input = Application.GetResourceStream(sourceUri).Stream)
            {
                using (IsolatedStorageFileStream output = isf.CreateFile(targetFileName))
                {
                    byte[] readBuffer = new byte[4096];
                    int bytesRead = -1;

                    while ((bytesRead = input.Read(readBuffer, 0, readBuffer.Length)) > 0)
                    {
                        output.Write(readBuffer, 0, bytesRead);
                    }
                }
            }
        }

        // 将文件从 Package 复制到 ApplicationData 的 Local 目录下
        private async Task CopyFileToApplicationData(Uri sourceUri, string targetFileName)
        {
            StorageFolder applicationFolder = ApplicationData.Current.LocalFolder;

            StorageFile sourceFile = await StorageFile.GetFileFromApplicationUriAsync(sourceUri);
            await sourceFile.CopyAsync(applicationFolder, targetFileName, NameCollisionOption.ReplaceExisting);
        }
    }
}


2、演示与图片中心相关的新增功能
MusicMediaLibrary/PictureMediaLibrary.xaml

<phone:PhoneApplicationPage
    x:Class="Demo.Media.PictureMediaLibrary"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:phone="clr-namespace:Microsoft.Phone.Controls;assembly=Microsoft.Phone"
    xmlns:shell="clr-namespace:Microsoft.Phone.Shell;assembly=Microsoft.Phone"
    xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
    xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
    FontFamily="{StaticResource PhoneFontFamilyNormal}"
    FontSize="{StaticResource PhoneFontSizeNormal}"
    Foreground="{StaticResource PhoneForegroundBrush}"
    SupportedOrientations="Portrait" Orientation="Portrait"
    mc:Ignorable="d"
    shell:SystemTray.IsVisible="True">

    <Grid Background="Transparent">
        <StackPanel Orientation="Vertical">

            <Image Name="img" Width="50" Height="50" />
            <Image Name="img2" Width="50" Height="50" Margin="0 10 0 0" />
            <Image Name="img3" Width="50" Height="50" Margin="0 10 0 0" />
            
            <Button x:Name="btnGet" Content="获取图片中心的图片的小缩略图和预览图" Click="btnGet_Click" />

            <Button x:Name="btnShare" Content="共享图片中心的指定的图片" Click="btnShare_Click"  />

        </StackPanel>
    </Grid>

</phone:PhoneApplicationPage>

MusicMediaLibrary/PictureMediaLibrary.xaml.cs

/*
 * 演示与图片中心相关的新增功能
 * 
 * 
 * 在 wp8 中新增了 Microsoft.Xna.Framework.Media.PhoneExtensions.MediaLibraryExtensions,其扩展了 MediaLibrary 类和 Picture 类
 *     Picture.GetPreviewImage() - 获取预览图(介于缩略图与原图之间)
 *     Picture.GetPath() - 获取文件路径,可以用于“共享”之类的场景,本例会介绍
 *     MediaLibrary.GetPathFromToken(fileToken) - 根据 token 获取媒体库文件的路径
 * 
 * 
 * 注:
 * 1、需要在 manifest 中增加配置 <Capability Name="ID_CAP_MEDIALIB_PHOTO" />
 * 2、在 wp8 中,保存在手机上的每个图片,系统都将为其自动创建两种缩略图:小缩略图和预览图
 */

using System.Linq;
using System.Windows;
using Microsoft.Phone.Controls;
using Microsoft.Xna.Framework.Media;
using Microsoft.Xna.Framework.Media.PhoneExtensions;
using Microsoft.Phone;
using Microsoft.Phone.Tasks;

namespace Demo.Media
{
    public partial class PictureMediaLibrary : PhoneApplicationPage
    {
        public PictureMediaLibrary()
        {
            InitializeComponent();
        }

        private void btnGet_Click(object sender, RoutedEventArgs e)
        {
            /*
             * MediaLibrary - 媒体库
             *     Pictures - 返回图片中心的全部图片
             *     SavedPictures - 返回图片中心的已保存图片
             *     RootPictureAlbum - 返回图片中心的所有根相册
             */

            MediaLibrary library = new MediaLibrary();

            if (library.Pictures.Count > 0)
            {
                // 获取图片中心的第一张图片
                Picture picture = library.Pictures.First();

                img.Source = PictureDecoder.DecodeJpeg(picture.GetImage()); // 获取原图
                img2.Source = PictureDecoder.DecodeJpeg(picture.GetThumbnail()); // 获取缩略图
                img3.Source = PictureDecoder.DecodeJpeg(picture.GetPreviewImage()); // 获取预览图
            }
        }

        private void btnShare_Click(object sender, RoutedEventArgs e)
        {
            MediaLibrary library = new MediaLibrary();

            if (library.Pictures.Count > 0)
            {
                Picture picture = library.Pictures.First();
                // 获取媒体文件路径
                string picturePath = picture.GetPath();

                // 由文件启动 app 时会传递过来文件的 token 值,用此方法可以根据 token 获取媒体库文件的路径
                // string picturePath = library.GetPathFromToken(fileToken);

                // 根据媒体文件路径共享之
                ShareMediaTask shareMediaTask = new ShareMediaTask();
                shareMediaTask.FilePath = picturePath;
                shareMediaTask.Show();
            }
        }
    }
}


3、演示后台音频播放的新增功能
MusicMediaLibrary/BackgroundAudio.xaml

<phone:PhoneApplicationPage
    x:Class="Demo.Media.BackgroundAudio"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:phone="clr-namespace:Microsoft.Phone.Controls;assembly=Microsoft.Phone"
    xmlns:shell="clr-namespace:Microsoft.Phone.Shell;assembly=Microsoft.Phone"
    xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
    xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
    FontFamily="{StaticResource PhoneFontFamilyNormal}"
    FontSize="{StaticResource PhoneFontSizeNormal}"
    Foreground="{StaticResource PhoneForegroundBrush}"
    SupportedOrientations="Portrait" Orientation="Portrait"
    mc:Ignorable="d"
    shell:SystemTray.IsVisible="True">

    <Grid Background="Transparent">
        <StackPanel Orientation="Vertical">

            <TextBlock x:Name="lblMsg" TextWrapping="Wrap" Text="BackgroundAudioPlayer 的 PlayStateChanged 事件有了事件参数 PlayStateChangedEventArgs" />

        </StackPanel>
    </Grid>

</phone:PhoneApplicationPage>

MusicMediaLibrary/BackgroundAudio.xaml.cs

/*
 * 演示后台音频播放的新增功能
 * 
 * 
 * 注:
 * 关于后台音频播放参见:http://www.cnblogs.com/webabcd/archive/2012/07/23/2604457.html
 */

using System;
using Microsoft.Phone.Controls;
using Microsoft.Phone.BackgroundAudio;

namespace Demo.Media
{
    public partial class BackgroundAudio : PhoneApplicationPage
    {
        public BackgroundAudio()
        {
            InitializeComponent();

            // 播放状态发生改变时
            BackgroundAudioPlayer.Instance.PlayStateChanged += Instance_PlayStateChanged;
        }

        void Instance_PlayStateChanged(object sender, EventArgs e)
        {
            /*
             * 以下是新增功能
             */

            // 将事件参数参数对象转换为 PlayStateChangedEventArgs
            PlayStateChangedEventArgs newEventArgs = (PlayStateChangedEventArgs)e;

            // BackgroundAudioPlayer 的当前的 PlayerState
            PlayState currentPlayState = newEventArgs.CurrentPlayState;

            // BackgroundAudioPlayer 在进入当前 PlayerState 时的前一个 PlayerState(如果没有此中间状态则 IntermediatePlayState 等于 CurrentPlayState)
            PlayState intermediatePlayState = newEventArgs.IntermediatePlayState;  
        }
    }
}



OK
[源码下载]

目录
相关文章
|
14天前
|
存储 文字识别 C#
.NET开源免费、功能强大的 Windows 截图录屏神器
今天大姚给大家分享一款.NET开源免费(基于GPL3.0开源协议)、功能强大、简洁灵活的 Windows 截图、录屏、Gif动图制作神器:ShareX。
|
1月前
|
Windows
Windows 命令提示符(CMD)操作(七):扩展命令和功能
Windows 命令提示符(CMD)操作(七):扩展命令和功能
49 0
|
4月前
|
安全 Linux 网络安全
Windows本地搭建Emby媒体库服务器并实现远程访问「内网穿透」
Windows本地搭建Emby媒体库服务器并实现远程访问「内网穿透」
|
7月前
|
Windows
windows103D对象,图片等隐藏
windows103D对象,图片等隐藏
61 0
|
7月前
|
开发工具 C# C++
Windows平台RTMP|RTSP播放器实现画面全屏功能
我们在Windows平台实现RTSP或者RTMP播放的时候,有个功能是绕不开的,那就是播放窗口全屏。本文就以大牛直播SDK(官方)的Windows播放器为例,大概讲下大概实现:
154 0
|
2月前
|
安全 Linux 网络安全
【Windows】搭建Emby媒体库服务器,实现无公网IP远程访问
【Windows】搭建Emby媒体库服务器,实现无公网IP远程访问
219 0
|
1月前
|
Windows
windows server 2019 安装NET Framework 3.5失败,提示:“安装一个或多个角色、角色服务或功能失败” 解决方案
windows server 2019 安装NET Framework 3.5失败,提示:“安装一个或多个角色、角色服务或功能失败” 解决方案
|
2月前
|
C# Windows
.NET开源的一个小而快并且功能强大的 Windows 动态桌面软件
.NET开源的一个小而快并且功能强大的 Windows 动态桌面软件
|
2月前
|
机器人 Linux 数据安全/隐私保护
Python办公自动化【Windows中定时任务、OS/linux 系统定时任务 、Python 钉钉发送消息、Python 钉钉发送图片】(九)-全面详解(学习总结---从入门到深化)
Python办公自动化【Windows中定时任务、OS/linux 系统定时任务 、Python 钉钉发送消息、Python 钉钉发送图片】(九)-全面详解(学习总结---从入门到深化)
66 0
|
3月前
|
存储 网络协议 安全
Windows Server 2022 安全功能重大更新
这篇文将介绍 Windows Server 2022 中的一些新增的安全功能,在 Windows Server 2019 的强大基础之上引入了许多创新功能。
60 0