将振幅转换回 .wav 文件 (C#) [英] Convert Amplitude BACK to .wav file (C#)

查看:38
本文介绍了将振幅转换回 .wav 文件 (C#)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我所做的是将波形文件转换为一个 short[] 数组中的幅度值,如下所示 C# 中 .wav 的平均幅度

What I have done is converted a wave file to amplitude values in a short[] array as found here Mean amplitude of a .wav in C#

我修改了这些值,现在想要转换回 .wav 格式或 byte[] 数组,以便何时可以写入字节文件.

I modified the values and now want to convert back to .wav format or a byte[] array which when can be written to a byte file.

推荐答案

void SetShortToBuffer(short val,byte[] outArray,int Offset)
{
    outArray[Offset] = (byte)(val & 0x00FF);
    Offset++;
    outArray[Offset] = (byte)((val >> 8) & 0x00FF);
}

byte[] ConvertShortArray(short[] Data,int Offset,int Count)
{
    byte[] helper = new byte[Count * sizeof(short)];

    int end = Offset+Count;
    int io=0;
    for (int i = Offset; i < end; i++)
    {
        SetShortToBuffer(Data[i], helper, io);
        io+=sizeof(short);
    }

    return helper; 
}

C 中,这不是问题,您可以简单地告诉编译器您之前声明的短数组现在应该被视为字节数组(简单转换),但是在失败之后C#unsafe 上下文之外我想出了这个代码 :)

In C this would not be an issue, you could simply tell the compiler that your previously declared short array should now be treated as a byte array (simple cast) but after failing to do so in C# outside of unsafe context I came up with this code :)

你可以使用 ConvertShortArray 函数来获取数据块,以防你的 wave 很大

You can use ConvertShortArray function to get chunks of data in case your wave is large

快速而肮脏的波头创建器,未经测试

Quick and dirty wave header creator, not tested

byte[] CreateWaveFileHeader(int SizeOfData, short ChannelCount, uint SamplesPerSecond, short BitsPerSample)
{

    short BlockAlign = (short)(ChannelCount * (BitsPerSample / 8));
    uint AverageBytesPerSecond = SamplesPerSecond * BlockAlign;

    List<byte> pom = new List<byte>();
    pom.AddRange(ASCIIEncoding.ASCII.GetBytes("RIFF"));
    pom.AddRange(BitConverter.GetBytes(SizeOfData + 36)); //Size + up to data
    pom.AddRange(ASCIIEncoding.ASCII.GetBytes("WAVEfmt "));
    pom.AddRange(BitConverter.GetBytes(((uint)16))); //16 For PCM
    pom.AddRange(BitConverter.GetBytes(((short)1))); //PCM FMT
    pom.AddRange(BitConverter.GetBytes(((short)ChannelCount)));
    pom.AddRange(BitConverter.GetBytes((uint)SamplesPerSecond));
    pom.AddRange(BitConverter.GetBytes((uint)AverageBytesPerSecond));
    pom.AddRange(BitConverter.GetBytes((short)BlockAlign));
    pom.AddRange(BitConverter.GetBytes((short)BitsPerSample));
    pom.AddRange(ASCIIEncoding.ASCII.GetBytes("data"));
    pom.AddRange(BitConverter.GetBytes(SizeOfData));

    return pom.ToArray();
}

这篇关于将振幅转换回 .wav 文件 (C#)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆