Playing a sound from a generated buffer in a Windo

2019-08-03 02:00发布

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条回答
放我归山
2楼-- · 2019-08-03 02:29

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();
    }
查看更多
登录 后发表回答