我有一个播放音调的媒体元素。只是一个纯音。 如果我从音调开始,最初的音调会打a。 如果我从80 ms或更长时间的空白开始,就不会打h。 如果我不是从空格开始,而是反复播放纯音(不断按一个按钮以运行相同的例程),则只会影响第一个。但是,如果我给它一些时间(也许几秒钟)来冷却,它又会打ic。 我将字节数组写入文件,然后以Audacity格式进行了查看-这是一个看起来不错的正弦波,没有打with。 我的设置中是否有引起这种情况的东西?
也许我应该使用较新的MediaPlayerElement,但我找不到如何播放wav数组的方法。
在代码中,我用'delay'常数控制初始延迟量。
const double delay = 0;
const double SampleRate = 44100.0;
MediaElement soundPlayer = new MediaElement();
private async Task PlayMyBeep(int frequency, int duration)
{
double DeltaFT = 2f * Math.PI * (double)frequency / (double)SampleRate;
double Sample;
//The total number of samples
double soundSamples = (SampleRate * duration) / 1000.0;
double quietSamples = (SampleRate * (delay/1000.0));
double TotalSamples = soundSamples + quietSamples;
// The WAV header
short NumChannels = 1;
short BitsPerSample = 16;
int ByteRate = (int)((double)(SampleRate * NumChannels * BitsPerSample) / 8.0);
short BlockAlign = (short)((double)(NumChannels * BitsPerSample) / 8.0);
int Bytes = (int)((double)(TotalSamples * NumChannels * BitsPerSample) / 8);
int BlockAlign_BitsPerSample = (BitsPerSample * 0x10000) + BlockAlign; //Shift BlockAlign
int[] Header = { 0x46464952, 36 + Bytes, 0x45564157, 0x20746D66, 16, 0x10001, (int)SampleRate, ByteRate, BlockAlign_BitsPerSample, 0x61746164, Bytes };
MemoryStream memoryStream = new MemoryStream(200 + Bytes);
BinaryWriter binaryWriter = new BinaryWriter(memoryStream);
for (int I = 0; I < Header.Length; I++) // write the header
binaryWriter.Write(Header[I]);
// write no tone for a while
for (double quietNum = 0; quietNum < quietSamples; quietNum++)
{
binaryWriter.Write((short)0);
}
// write the tone
for (double sampleNum = 0; sampleNum < soundSamples; sampleNum++)
{
Sample = (short)((double)short.MaxValue * Math.Sin(DeltaFT * sampleNum));
binaryWriter.Write((short)Sample);
}
binaryWriter.Flush(); // empty out any that is left
//turn this into an array to be played
byte[] byteArray = memoryStream.ToArray();
// write the memory stream to a file - to see what the waveform looks like.
StorageFolder localFolder = ApplicationData.Current.LocalFolder;
StorageFile localFile = await localFolder.CreateFileAsync("Test.wav", CreationCollisionOption.ReplaceExisting);
await FileIO.WriteBytesAsync(localFile, byteArray);
memoryStream.Seek(0, SeekOrigin.Begin);
var soundSource = memoryStream.AsRandomAccessStream();
soundSource.Seek(0);
soundPlayer.SetSource(soundSource, "audio/wav");
soundPlayer.Play();
}