问题
I new in windows phone sdk. I can't find example of playing a sound from a generated buffer in a Windows phone app. Help pls.
i found this example:
byte] buffer = new byte[44100 * 2 * 5];
float t = 0;
for (int i = 0; i < 44100 * 2 * 5; i += 2)
{
short val = (short)(Math.Sin(t * 2 * Math.PI * 440) * short.MaxValue);
buffer[i] = (byte)(val & 0xFF);
buffer[i + 1] = (byte)(val >> 8);
t += 1 / 44100.0f;
}
sf = new SoundEffect(buffer, 44100, AudioChannels.Mono);
// Play.
sf.Play();
but it's crash with error A first chance exception of type 'System.InvalidOperationException' occurred in Microsoft.Xna.Framework.ni.dll An exception of type 'System.InvalidOperationException' occurred in Microsoft.Xna.Framework.ni.dll but was not handled in user code
回答1:
You need to call the FrameworkDispatcher.Update
.
(See exception: FrameworkDispatcher.Update has not been called. Regular FrameworkDispatcher.Update calls are necessary for fire and forget sound effects and framework events to function correctly. See http://go.microsoft.com/fwlink/?LinkId=193853 for details.)
Set up a timer in your constructor:
var dt = new DispatcherTimer();
dt.Interval = TimeSpan.FromMilliseconds(33);
dt.Tick += new EventHandler(Tick);
dt.Start();
And a Tick event handler:
void Tick(object sender, EventArgs e)
{
try
{
FrameworkDispatcher.Update();
}
catch (Exception ex)
{
if (Debugger.IsAttached)
{
Debugger.Break();
}
}
}
Should work with for example a play button in your app. I have also added one line to your code: var soundInstance = sf.CreateInstance();
private void appBarPlayButton_Click(object sender, EventArgs e)
{
byte[] buffer = new byte[44100 * 2 * 5];
float t = 0;
for (int i = 0; i < 44100 * 2 * 5; i += 2)
{
short val = (short)(Math.Sin(t * 2 * Math.PI * 440) * short.MaxValue);
buffer[i] = (byte)(val & 0xFF);
buffer[i + 1] = (byte)(val >> 8);
t += 1 / 44100.0f;
}
var sf = new SoundEffect(buffer, 44100, AudioChannels.Mono);
var soundInstance = sf.CreateInstance();
// Play.
sf.Play();
}
来源:https://stackoverflow.com/questions/26697904/playing-a-sound-from-a-generated-buffer-in-a-windows-phone-app