play audio periodically from a memory stream c#

806 views Asked by At

I have some buffer containing samples of sinus which I want to be played from a memory stream periodically. Is there any efficient way to play it without having gaps in time? I try to make my own signal generator (I know that are some libraries providing that but I want to generate it by myself).

The platform is Windows Phone 8.1 silverlight

Update: the code is taken from this forum somewhere

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 samplesPerSecond = 44100;

        {
            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);
            }
        }


    }
1

There are 1 answers

0
axcelenator On BEST ANSWER

Here how I did it - just create a new SoundEffectInstance object and set it to the return value of SoundEffect.CreateInstance.

https://msdn.microsoft.com/en-us/library/dd940203.aspx

SoundEffect mySoundPlay = new SoundEffect(mStrm.ToArray(), 16000,AudioChannels.Mono);
SoundEffectInstance instance = mySoundPlay.CreateInstance();
instance.IsLooped = true;
instance.Play();