从 Windows 手机应用程序中生成的缓冲区播放声音 [英] Playing a sound from a generated buffer in a Windows phone app
问题描述
我是 Windows Phone sdk 的新手.我找不到从 Windows 手机应用程序中生成的缓冲区播放声音的示例.请帮助.
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.
我找到了这个例子:
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();
但它因错误而崩溃Microsoft.Xna.Framework.ni.dll 中发生了System.InvalidOperationException"类型的第一次机会异常Microsoft.Xna.Framework.ni.dll 中出现System.InvalidOperationException"类型的异常,但未在用户代码中处理
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
推荐答案
你需要调用FrameworkDispatcher.Update
.
(见例外:尚未调用 FrameworkDispatcher.Update.定期的 FrameworkDispatcher.Update 调用对于触发和遗忘声音效果和框架事件正确运行是必要的.请参阅 http://go.microsoft.com/fwlink/?LinkId=193853 了解详情.)
(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();
还有一个 Tick 事件处理程序:
And a Tick event handler:
void Tick(object sender, EventArgs e)
{
try
{
FrameworkDispatcher.Update();
}
catch (Exception ex)
{
if (Debugger.IsAttached)
{
Debugger.Break();
}
}
}
应该与您的应用中的播放按钮一起使用.我还在您的代码中添加了一行:var soundInstance = sf.CreateInstance();
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();
}
这篇关于从 Windows 手机应用程序中生成的缓冲区播放声音的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!