繁体   English   中英

使用Naudio播放Wave of Stream

[英]using Naudio to play Stream of Wave

我想更改波形文件的比特率。

所以我在网上搜索了一下,发现wave文件包含一个44字节长的标头,而25、26、27和28个字节用于存储wave文件的比特率

因此,我将wave存入一个字节数组中,然后更改用于存储wave比特率的字节值。

这是代码:

        private int sampleRate;
        private byte[] ByteArr;
        private MemoryStream ByteMem;
        ByteArr = null;
        ByteMem = null;
        ByteArr = File.ReadAllBytes(pathOfWav.Text);
        sampleRate = BitConverter.ToInt32(ByteArr, 24) * 2;
        Array.Copy(BitConverter.GetBytes(sampleRate), 0, ByteArr, 24, 4);
        ByteMem = new MemoryStream(ByteArr);

在这里我将Wave文件的位置存储在pathOfWav.Text这是一个文本框,然后将wave文件的所有字节存储在ByteArr然后将4字节(从25到28)转换为Int32并将其乘以2以提高速度语音与存储在值sampleRate之后,我改变了以前的ByteArr与比特率的新值sampleRate ,然后我实例的新的MemoryStream。

我的问题是,如何使用Naudio播放新的Wave流?

您解决了这个问题吗? 根据您的评论,如果只需要更改sampleRate,那么为什么要使用NAudio? 您可以使用默认的可用播放器,例如MediaPlayer / SoundPlayer。 如果是这样,您可以参考以下代码。 我添加了一种更改采样率的方法。 尽管您可以单独编写waveFormat或追加,但我仅提及采样率及其相关字段。 我正在读取整个文件,然后关闭然后打开以逐部分编写文件。

(C#中“ WaveHeader格式”的原始参考: http : //www.codeproject.com/Articles/15187/Concatenating-Wave-Files-Using-C-2005

public void changeSampleRate(string waveFile, int sampleRate)
{
    if (waveFile == null)
    {
        return;
    }

    /* you can add additional input validation code here */

    /* open for reading */
    FileStream fs = new FileStream(waveFile, FileMode.Open, FileAccess.Read);

    /* get the channel and bits per sample value -> required for calculation */
    BinaryReader br = new BinaryReader(fs);
    int length = (int)fs.Length - 8;
    fs.Position = 22;
    short channels = br.ReadInt16();
    fs.Position = 34;
    short BitsPerSample = br.ReadInt16();

    byte[] arrfile = new byte[fs.Length];
    fs.Position = 0;
    fs.Read(arrfile, 0, arrfile.Length); /* read entire file */
    br.Close();
    fs.Close();

    /* now open for writing */
    fs = new FileStream(waveFile, FileMode.Open, FileAccess.Write);

    BinaryWriter bw = new BinaryWriter(fs);

    bw.BaseStream.Seek(0, SeekOrigin.Begin);
    bw.Write(arrfile, 0, 24); //no change till this point 

    /* refer to waveFormat header */
    bw.Write(sampleRate);
    bw.Write((int)(sampleRate * ((BitsPerSample * channels) / 8)));
    bw.Write((short)((BitsPerSample * channels) / 8));

    /* you can keep the same data from here */
    bw.Write(arrfile, 34, arrfile.Length - 34);

    bw.Close();

    fs.Close();
}

现在,您可以调用上述方法并以不同的采样率播放wave文件:

    changeSampleRate(yourWaveFileToPlay, requiredSampleRate);

    MediaPlayer mp = new MediaPlayer();

    mp.Open(new Uri(yourWaveFileToPlay, UriKind.Absolute));

    mp.Play();

要更改WAV文件的比特率,您不能仅更新其格式块。 实际上,您必须以新的采样率/比特深度(假设它是PCM)或为编解码器(如果不是PCM)选择其他比特率来重新编码。 我在这里写了一篇文章,介绍如何在各种音频格式之间进行转换,包括在不同风味的PCM之间进行转换。 同一篇文章还将说明如果您要更改采样率而不是比特率,该怎么办。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM