【问题标题】:Playing simple sounds in a Windows Store (Metro) application在 Windows Store (Metro) 应用程序中播放简单的声音
【发布时间】:2013-06-17 01:19:29
【问题描述】:

我正在使用 XAML 和 C# 构建一个 Windows Store (Metro) 应用程序。我想弹一个简单的音调,并且能够控制持续时间和音高;我们以前用 Console.Beep 做的那种事情。

我找到了 Play dynamically-created simple sounds in C# without external libraries,但它引用了 SoundPlayer(System.Media 命名空间),这种类型的应用程序似乎不支持它(当然,除非我遗漏了什么)。

有没有人有在 Metro 应用程序中生成声音(不播放 wav 文件)的示例?

【问题讨论】:

    标签: c# windows-8 microsoft-metro


    【解决方案1】:

    基于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,所以它很灵活。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-11-01
      • 2013-01-18
      • 2015-02-10
      相关资源
      最近更新 更多