Playing a sound from a generated buffer in a Windows phone app

陌路散爱 提交于 2019-12-11 13:54:17

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!