我有一个内存WAV流,我可以使用
播放 mStrm.Seek(0, SeekOrigin.Begin);
new System.Media.SoundPlayer(mStrm).Play();
我试图看看我如何使用相同的流并在UWP应用程序中播放它。我尝试了以下代码
MediaElement soundPlayer = new MediaElement();
var soundSource = mStrm.AsRandomAccessStream();
soundSource.Seek(0);
soundPlayer.SetSource(soundSource, "audio/wav");
soundPlayer.Play();
但我收到以下错误
MF_MEDIA_ENGINE_ERR_SRC_NOT_SUPPORTED : HRESULT - 0x80000013
添加我从网上获取的音频合成代码。
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;
writer.Write(0x46464952);
writer.Write(fileSize);
writer.Write(0x45564157);
writer.Write(0x20746D66);
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;
double 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);
MediaElement soundPlayer = new MediaElement();
var soundSource = mStrm.AsRandomAccessStream();
soundSource.Seek(0);
soundPlayer.SetSource(soundSource, "audio/wav");
soundPlayer.Play();
writer.Dispose();
mStrm.Dispose();
}
我在for循环中传递不同八度音的不同音符频率,持续时间为1000毫秒。
对此有任何帮助表示赞赏。
谢谢, Teja公司