Windows Phone 7:Silverlight和播放音乐

时间:2011-08-15 22:50:11

标签: silverlight windows-phone-7 silverlight-4.0 xna-4.0

我在WP7中构建了一个简单的游戏,我正在尝试使用MediaPlayer为其添加背景音乐。问题是它只是用

炸弹

{“发生意外错误。”} System.Exception {System.InvalidOperationException}

代码

try
                {
                    MediaPlayer.Stop();
                    // Timer to run the XNA internals (MediaPlayer is from XNA)
                    DispatcherTimer dt = new DispatcherTimer();
                    dt.Interval = TimeSpan.FromMilliseconds(33);
                    dt.Tick += delegate { try { FrameworkDispatcher.Update(); } catch { } };
                    dt.Start();

                    Uri pathToFile = new Uri("Audio/music.m4a", UriKind.Relative);
                    Song playingSong = Song.FromUri("Music", pathToFile);
                    MediaPlayer.Play(playingSong);
                }
                catch (Exception e)
                {
                    musicFailed = true;
                    Console.WriteLine("Exception: {0}", e.ToString());
                    MessageBox.Show("Warning, music failed to play however you can still continue to play your game.");
                }
            }

我尝试了一些调整,将文件转换为mp3,不同路径等。文件标记为复制始终和内容类型我也尝试删除调度程序,因为不知道它是什么。< / p>

2 个答案:

答案 0 :(得分:1)

如果您可以将音频文件转换为WAV格式,可以尝试使用XNA SoundEffect和SoundEffectInstance类:

SoundEffect se = SoundEffect.FromStream(isolatedStorageFileStream);
SoundEffectInstance sei = se.CreateInstance();
sei.Play();

为此,您需要引用XNA库(Microsoft.XNA.Framework)并以这种方式初始化框架:

<强> App.xaml中:

<Application>
    <Application.ApplicationLifetimeObjects>
        <local:XNAFrameworkDispatcherService />
        ...
    </Application.ApplicationLifetimeObjects>    
</Application>

在app命名空间的某处创建此类(前一个xaml中的“local”引用此命名空间):

public class XNAFrameworkDispatcherService : IApplicationService
{
    private DispatcherTimer frameworkDispatcherTimer;
    public XNAFrameworkDispatcherService()
    {
        this.frameworkDispatcherTimer = new DispatcherTimer();
        this.frameworkDispatcherTimer.Interval = TimeSpan.FromTicks(333333);
        this.frameworkDispatcherTimer.Tick += frameworkDispatcherTimer_Tick;
        FrameworkDispatcher.Update();
    }
    void frameworkDispatcherTimer_Tick(object sender, EventArgs e) { FrameworkDispatcher.Update(); }
    void IApplicationService.StartService(ApplicationServiceContext context) { this.frameworkDispatcherTimer.Start(); }
    void IApplicationService.StopService() { this.frameworkDispatcherTimer.Stop(); }
}

答案 1 :(得分:0)

你的问题是你的计时器可能没有在第一次打勾时被解雇,而FrameworkDispatcher.Update()没有跑。然后Play会抛出System.InvalidOperationException

更好地在您的应用程序中调度XNA Events全局。

完整指南:XNAAsyncDispatcher