播放双阵列中的声音



我有一个问题,表面上看起来很简单,但我有很多问题要解决。

我有2个双阵列(左通道和右通道),包含由DAQ在350KHz下采样的数据,我已将其下变频至44.1KHz。

我想做的就是拿着这两个数组播放它们,但似乎有太多的选项可以用来输出声音,如directx、NAudio等,所以我希望有人能建议我什么是最好的方法,也许能给我指明正确的方向!

提前感谢您的任何建议,我们将不胜感激。

Dave

NAudio是我听过人们多次提到的一个选项(你也提到过)。我知道这是一个开源的第三方库。你可能想看看这个。

不幸的是,据我所知,在我看来,DirectX正在消亡,多年来MS已经改变了他们对一些不同事物的推动,现在他们似乎正在推动人们使用XNA,这实际上是一个完整的框架,当你在XNA中制作项目时,它可以在桌面环境中的Windows、Xbox 360或Windows Phone上运行。对我来说,Windows Phone并不是一个大块头,因为MS似乎不是移动世界中的一个大玩家,但一个在Xbox上运行的应用程序对我很有吸引力。但我在XNA框架/架构中看到了一些常规.NET框架所缺乏的更好的功能,包括视频播放和音频播放。除此之外,我不知道太多细节,因为我还没有开始在XNA中开发。

此外,您可能希望在不使用任何第三方库的情况下,使用System.Media.SoundPlayer直接在.NET中播放它们。

我找到了下面的代码,它使用它来播放一个简单的正弦波。它生成声音样本,然后将其提供给MemoryStream,然后使用SoundPlayer播放。SoundPlayer本身采用WAV格式的Stream,我知道它可以播放立体声,但我不需要立体声,所以我没有研究如何将其添加到WAV文件格式中。我非常喜欢的是,它不需要第三方DLL。如果这种方法对你有用,那么它就是:

using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Windows.Forms;
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;
    // var encoding = new System.Text.UTF8Encoding();
    writer.Write(0x46464952); // = encoding.GetBytes("RIFF")
    writer.Write(fileSize);
    writer.Write(0x45564157); // = encoding.GetBytes("WAVE")
    writer.Write(0x20746D66); // = encoding.GetBytes("fmt ")
    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;
        // '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);
        }
    }
    mStrm.Seek(0, SeekOrigin.Begin);
    new System.Media.SoundPlayer(mStrm).Play();
    writer.Close();
    mStrm.Close();
} // public static void PlayBeep(UInt16 frequency, int msDuration, UInt16 volume = 16383)

当然,如果你选择最后一个选项,你需要弄清楚如何将立体声格式化为WAV格式,并亲自研究(或询问)。编码快乐!

最新更新