从MemoryStream Windows Phone 8.1播放wav文件

时间:2015-06-16 12:38:17

标签: c# xna windows-phone-8.1 wav memorystream

我在这个代表wav文件的论坛中复制了一些代码并将其写入MemoryStream。我点击一个传入了一些变量的按钮时尝试播放它:PlayBeep(8000,500,16383); 但模拟器崩溃并说:

  

发生了'System.InvalidOperationException'类型的异常   Microsoft.Xna.Framework.ni.dll但未在用户代码中处理

     

其他信息:尚未调用FrameworkDispatcher.Update

以下是代码:

public static void PlayBeep(UInt16 frequency, int msDuration, UInt16 volume = 16383)
    {
        var mStrm = new MemoryStream();
        BinaryWriter writer = new BinaryWriter(mStrm);

        const double TAU = 2 * Math.PI;
        int formatChunkSize = 16;
        int headerSize = 8;
        short formatType = 1;
        short tracks = 1;
        int samplesPerSecond = 44100;
        short bitsPerSample = 16;
        short frameSize = (short)(tracks * ((bitsPerSample + 7) / 8));
        int bytesPerSecond = samplesPerSecond * frameSize;
        int waveSize = 4;
        int samples = (int)((decimal)samplesPerSecond * msDuration / 1000);
        int dataChunkSize = samples * frameSize;
        int fileSize = waveSize + headerSize + formatChunkSize + headerSize + dataChunkSize;
        // var encoding = new System.Text.UTF8Encoding();
        writer.Write(0x46464952); // = encoding.GetBytes("RIFF")
        writer.Write(fileSize);
        writer.Write(0x45564157); // = encoding.GetBytes("WAVE")
        writer.Write(0x20746D66); // = encoding.GetBytes("fmt ")
        writer.Write(formatChunkSize);
        writer.Write(formatType);
        writer.Write(tracks);
        writer.Write(samplesPerSecond);
        writer.Write(bytesPerSecond);
        writer.Write(frameSize);
        writer.Write(bitsPerSample);
        writer.Write(0x61746164); // = encoding.GetBytes("data")
        writer.Write(dataChunkSize);
        {
            double theta = frequency * TAU / (double)samplesPerSecond;
            // 'volume' is UInt16 with range 0 thru Uint16.MaxValue ( = 65 535)
            // we need 'amp' to have the range of 0 thru Int16.MaxValue ( = 32 767)
            double amp = volume >> 2; // so we simply set amp = volume / 2
            for (int step = 0; step < samples; step++)
            {
                short s = (short)(amp * Math.Sin(theta * (double)step));
                writer.Write(s);
            }
        }

        mStrm.Seek(0, SeekOrigin.Begin);
        SoundEffect mySoundEffect = SoundEffect.FromStream(mStrm);
        //mySoundEffect.Play(); //Crashing here


        writer.Close();
        mStrm.Close();
    }

0 个答案:

没有答案