Windows Phone 7 : Silverlight and playing Music
I have built a simple game in WP7 and I am trying to add background music to it using MediaPlayer. The problem is it just bombs with
{"An unexpected error has occurred."} System.Exception {System.InvalidOperationException}
Code
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());
开发者_StackOverflow中文版 MessageBox.Show("Warning, music failed to play however you can still continue to play your game.");
}
}
I tried a few tweaks, converting file to mp3, different paths etc. The file is marked for copy always and content type I also tried removing the Dispatcher as dont know what that is for.
If you can convert your audio files to WAV format, you can try using the XNA SoundEffect and SoundEffectInstance classes:
SoundEffect se = SoundEffect.FromStream(isolatedStorageFileStream);
SoundEffectInstance sei = se.CreateInstance();
sei.Play();
For this to work, you will need to reference the XNA library (Microsoft.XNA.Framework) and initialize the framework in this way:
App.xaml:
<Application>
<Application.ApplicationLifetimeObjects>
<local:XNAFrameworkDispatcherService />
...
</Application.ApplicationLifetimeObjects>
</Application>
And create this class somewhere in the app namespace ("local" in the previous xaml references this namespace):
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(); }
}
Your problem is that your timer maybe not fired the first tick and FrameworkDispatcher.Update()
not ran. Then Play
throws a System.InvalidOperationException
.
Better dispatch XNA Events global in your Application.
Complete Guide: XNAAsyncDispatcher
精彩评论