簡體   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