我正在使用XAML和C#构建Windows应用商店(Metro)应用程序。我想演奏一个简单的音调,并能够控制持续时间和音高;我们以前用Console.Beep做的事情。
我找到了Play dynamically-created simple sounds in C# without external libraries,但它引用了SoundPlayer(System.Media命名空间),这种类型的应用程序似乎不支持(除非我当然缺少某些东西)。
有没有人在Metro应用程序中有一个生成声音(不播放wav文件)的例子?
答案 0 :(得分:9)
根据this文章,以下对我有用:
public async Task<IRandomAccessStream> BeepBeep(int Amplitude, int Frequency, int Duration)
{
double A = ((Amplitude * (System.Math.Pow(2, 15))) / 1000) - 1;
double DeltaFT = 2 * Math.PI * Frequency / 44100.0;
int Samples = 441 * Duration / 10;
int Bytes = Samples * 4;
int[] Hdr = { 0X46464952, 36 + Bytes, 0X45564157, 0X20746D66, 16, 0X20001, 44100, 176400, 0X100004, 0X61746164, Bytes };
InMemoryRandomAccessStream ims = new InMemoryRandomAccessStream();
IOutputStream outStream = ims.GetOutputStreamAt(0);
DataWriter dw = new DataWriter(outStream);
dw.ByteOrder = ByteOrder.LittleEndian;
for (int I = 0; I < Hdr.Length; I++)
{
dw.WriteInt32(Hdr[I]);
}
for (int T = 0; T < Samples; T++)
{
short Sample = System.Convert.ToInt16(A * Math.Sin(DeltaFT * T));
dw.WriteInt16(Sample);
dw.WriteInt16(Sample);
}
await dw.StoreAsync();
await outStream.FlushAsync();
return ims;
}
private async void Button_Click(object sender, RoutedEventArgs e)
{
var beepStream = await BeepBeep(200, 3000, 250);
mediaElement1.SetSource(beepStream, string.Empty);
mediaElement1.Play();
}
它使用MediaElement
进行播放,但由于源是自动生成的IRandomAccessStream
,因此它非常灵活。