模拟器上的Windows phone 8 - 为什么我不能播放音频文件?

时间:2013-01-19 19:58:04

标签: mp3 media-player windows-phone-8 filenotfoundexception

我正在转换一个用Silverlight编写的应用程序,到目前为止,我已经成功地解决了所有问题,除了一个:

出于某种原因,模拟器拒绝播放应用程序的任何音频文件,它甚至不会抛出异常。我已经检查了,在铃声类别中它可以发出声音。

原始代码是:

<Grid x:Name="sharedFullScreenFilePathContainer"
Tag="{Binding StringFormat=\{0\},Converter={StaticResource fullScreenImageConverter}}">

    <Image x:Name="fullScreenImage" Stretch="Fill"
Source="{Binding ElementName=sharedFullScreenFilePathContainer,Path=Tag, StringFormat=../Assets/images/\{0\}.jpg}"
ImageFailed="onFullScreenImageFailedToLoad" MouseLeftButtonDown="onPressedOnFullScreenImage" />

    <MediaElement x:Name="mediaPlayer" AutoPlay="True"
Source="{Binding ElementName=sharedFullScreenFilePathContainer,Path=Tag, StringFormat=../Assets/sounds/\{0\}.wma}" />
</Grid>

所以,我确实显示了我设置到此项目上下文的图像,但是我设置到它的路径上确实存在的声音没有播放(我已经在“Bin”文件夹中检查过)。

我尝试使用代码而不是xaml,但我仍然遇到同样的问题。

我试过这个(虽然它通常用于背景音乐):

AudioTrack audioTrack = new AudioTrack(new Uri("../Assets/sounds/" + fileToOpen, UriKind.Relative), "", "", "", null);
BackgroundAudioPlayer player = BackgroundAudioPlayer.Instance;
player.Track = audioTrack;
player.Play();

它没有发挥任何作用,也没有任何例外。

我也尝试了下一个代码,但它抛出异常(找不到文件异常)可能是因为我没有正确调用它:

Stream stream = TitleContainer.OpenStream("@Assets/sounds/" + fileToOpen);
SoundEffect effect = SoundEffect.FromStream(stream);
FrameworkDispatcher.Update();
effect.Play();

我也尝试过使用wma文件,但它也没有用。

我还尝试使用mp3文件的“copy to output directory”参数(“always”和“only new”)和“build action”参数(to“none”和“content”) )。什么都没有帮助。

任何人都可以帮助我吗?我没有为Silverlight / WP开发很长一段时间,我也找不到如何解决它。

顺便说一句,因为以后我需要知道声音何时播放完毕(并且还能够停止播放),我还是想使用代码。如果你也可以告诉我怎么做,我会很高兴(如果需要,我可以在新的帖子上问它)。


编辑: 好吧,我发现了问题:我在使用 MediaPlayer.Play()方法时遇到了一个奇怪的异常,在查看了异常后,我发现它已经知道了问题,我需要在调用Play()方法之前调用 FrameworkDispatcher.Update();

所以解决方案是做这样的事情:

Song song = Song.FromUri(...);
MediaPlayer.Stop(); 
FrameworkDispatcher.Update();
MediaPlayer.Play(song);

例外是:

System.Windows.ni.dll“

中发生'System.InvalidOperationException'

我找到了解决方案here

现在问题是为什么,为什么我在Windows手机的演示中没有找到与之相关的任何内容?另外,我想知道这个功能是做什么的。


好的,既然没有人给我这两个问题的答案,我仍然希望给予赏金,我会问另一个问题:

如果除了使用Windows Phone的MediaPlayer类之外确实没有解决方案,我如何捕获播放音频文件的结束事件?即使获取音频文件持续时间也不起作用(无论我尝试使用哪个类,都会保持返回0长度...)

5 个答案:

答案 0 :(得分:2)

BackgroundAudioPlayer可以从隔离存储或远程URI播放文件,这就是为什么你可以在这里做任何事情!

如果您的文件是应用程序中的资源,则必须先将它们复制到隔离的商店,然后在隔离的商店中引用BackgroundAudioPlayer中的文件。

    private void CopyToIsolatedStorage()
    {
        using (IsolatedStorageFile storage = IsolatedStorageFile.GetUserStoreForApplication())
        {
            string[] files = new string[] 
                { "Kalimba.mp3", 
                    "Maid with the Flaxen Hair.mp3", 
                    "Sleep Away.mp3" };

            foreach (var _fileName in files)
            {
                if (!storage.FileExists(_fileName))
                {
                    string _filePath = "Audio/" + _fileName;
                    StreamResourceInfo resource = Application.GetResourceStream(new Uri(_filePath, UriKind.Relative));

                    using (IsolatedStorageFileStream file = storage.CreateFile(_fileName))
                    {
                        int chunkSize = 4096;
                        byte[] bytes = new byte[chunkSize];
                        int byteCount;

                        while ((byteCount = resource.Stream.Read(bytes, 0, chunkSize)) > 0)
                        {
                            file.Write(bytes, 0, byteCount);
                        }
                    }
                }
            }
        }
    }

然后你可以列出你的歌曲

    private static List<AudioTrack> _playList = new List<AudioTrack>
    {
        new AudioTrack(new Uri("Kalimba.mp3", UriKind.Relative), 
                        "Kalimba", 
                        "Mr. Scruff", 
                        "Ninja Tuna", 
                        null),

        new AudioTrack(new Uri("Maid with the Flaxen Hair.mp3", UriKind.Relative), 
                        "Maid with the Flaxen Hair", 
                        "Richard Stoltzman", 
                        "Fine Music, Vol. 1", 
                        null),

        new AudioTrack(new Uri("Sleep Away.mp3", UriKind.Relative), 
                        "Sleep Away", 
                        "Bob Acri", 
                        "Bob Acri", 
                        null),

        // A remote URI
        new AudioTrack(new Uri("http://traffic.libsyn.com/wpradio/WPRadio_29.mp3", UriKind.Absolute), 
                        "Episode 29", 
                        "Windows Phone Radio", 
                        "Windows Phone Radio Podcast", 
                        null)
    };

播放你的曲目!

    private void PlayNextTrack(BackgroundAudioPlayer player)
    {
        if (++currentTrackNumber >= _playList.Count)
        {
            currentTrackNumber = 0;
        }

        PlayTrack(player);
    }

    private void PlayPreviousTrack(BackgroundAudioPlayer player)
    {
        if (--currentTrackNumber < 0)
        {
            currentTrackNumber = _playList.Count - 1;
        }

        PlayTrack(player);
    }

    private void PlayTrack(BackgroundAudioPlayer player)
    {
        // Sets the track to play. When the TrackReady state is received, 
        // playback begins from the OnPlayStateChanged handler.
        player.Track = _playList[currentTrackNumber];
    }

答案 1 :(得分:2)

如果您希望MediaElement在您的代码中运行,您可以执行以下操作!

        MediaElement me = new MediaElement();
        // Must add the MediaElement to some UI container on 
        // your page or some UI-control, otherwise it will not play!
        this.LayoutRoot.Children.Add(me);
        me.Source = new Uri("Assets/AwesomeMusic.mp3", UriKind.RelativeOrAbsolute);
        me.Play();

答案 2 :(得分:0)

音轨播放存储在独立存储中或通过互联网流式传输的音频文件。

答案 3 :(得分:0)

播放应用程序包中存储的音频文件对我来说很好。我在项目文件夹Resources \ Alarms中得到了名为“Alarm01.wma”的文件。然后我播放这样的声音:

using Microsoft.Xna.Framework.Media;
...
Song s = Song.FromUri("alarm", new Uri(@"Resources/Alarms/Alarm01.wma", UriKind.Relative));
MediaPlayer.Play(s);

另请不要忘记参考 Microsoft.Xna.Framework 库。

我想它应该适用于存储在IsolatedStorage中的mp3文件和文件。

答案 4 :(得分:0)

使用MediaElement,这可以播放存储在您的应用程序中的媒体文件,但在应用程序停止时停止播放(您可以为您的应用程序提前运行,以便它继续运行,但它不能很好地工作)

在您的XAML中:

        <Button x:Name="PlayFile"
                Click="PlayFile_Click_1"
                Content="Play mp3" />

在您的代码背后:

    MediaElement MyMedia = new MediaElement();
    // Constructor
    public MainPage()
    {
        InitializeComponent();

        this.LayoutRoot.Children.Add(MyMedia);

        MyMedia.CurrentStateChanged += MyMedia_CurrentStateChanged;
        MyMedia.MediaEnded += MyMedia_MediaEnded;
    }

    void MyMedia_MediaEnded(object sender, RoutedEventArgs e)
    {
        System.Diagnostics.Debug.WriteLine("Ended event " + MyMedia.CurrentState.ToString());
        // Set the source to null, force a Close event in current state
        MyMedia.Source = null;
    }

    void MyMedia_CurrentStateChanged(object sender, RoutedEventArgs e)
    {

        switch (MyMedia.CurrentState)
        {
            case System.Windows.Media.MediaElementState.AcquiringLicense:
                break;
            case System.Windows.Media.MediaElementState.Buffering:
                break;
            case System.Windows.Media.MediaElementState.Closed:
                break;
            case System.Windows.Media.MediaElementState.Individualizing:
                break;
            case System.Windows.Media.MediaElementState.Opening:
                break;
            case System.Windows.Media.MediaElementState.Paused:
                break;
            case System.Windows.Media.MediaElementState.Playing:
                break;
            case System.Windows.Media.MediaElementState.Stopped:
                break;
            default:
                break;
        }

        System.Diagnostics.Debug.WriteLine("CurrentState event " + MyMedia.CurrentState.ToString());
    }

    private void PlayFile_Click_1(object sender, RoutedEventArgs e)
    {
        // Play Awesome music file, stored as content in the Assets folder in your app
        MyMedia.Source = new Uri("Assets/AwesomeMusic.mp3", UriKind.RelativeOrAbsolute);
        MyMedia.Play();
    }
相关问题