【发布时间】:2013-10-01 08:53:15
【问题描述】:
我目前正在尝试使用此算法对波形文件进行音高转换
https://sites.google.com/site/mikescoderama/pitch-shifting
这是我使用上述实现的代码,但没有运气。输出的波形文件似乎已损坏或无效。
代码很简单,除了音高偏移算法:)
- 它加载一个波形文件,它读取波形文件数据并将其放入一个 byte[] 数组。
- 然后它将字节数据“标准化”为 -1.0f 到 1.0f 格式(如 由音高变换算法的创建者要求)。
- 它应用音高偏移算法,然后转换回 将数据标准化为 bytes[] 数组。
- 最后保存了一个与原wave头相同的wave文件 文件和音高偏移数据。
我错过了什么吗?
static void Main(string[] args)
{
// Read the wave file data bytes
byte[] waveheader = null;
byte[] wavedata = null;
using (BinaryReader reader = new BinaryReader(File.OpenRead("sound.wav")))
{
// Read first 44 bytes (header);
waveheader= reader.ReadBytes(44);
// Read data
wavedata = reader.ReadBytes((int)reader.BaseStream.Length - 44);
}
short nChannels = BitConverter.ToInt16(waveheader, 22);
int sampleRate = BitConverter.ToInt32(waveheader, 24);
short bitRate = BitConverter.ToInt16(waveheader, 34);
// Normalized data store. Store values in the format -1.0 to 1.0
float[] in_data = new float[wavedata.Length / 2];
// Normalize wave data into -1.0 to 1.0 values
using(BinaryReader reader = new BinaryReader(new MemoryStream(wavedata)))
{
for (int i = 0; i < in_data.Length; i++)
{
if(bitRate == 16)
in_data[i] = reader.ReadInt16() / 32768f;
if (bitRate == 8)
in_data[i] = (reader.ReadByte() - 128) / 128f;
}
}
//PitchShifter.PitchShift(1f, in_data.Length, (long)1024, (long)32, sampleRate, in_data);
// Backup wave data
byte[] copydata = new byte[wavedata.Length];
Array.Copy(wavedata, copydata, wavedata.Length);
// Revert data to byte format
Array.Clear(wavedata, 0, wavedata.Length);
using (BinaryWriter writer = new BinaryWriter(new MemoryStream(wavedata)))
{
for (int i = 0; i < in_data.Length; i++)
{
if(bitRate == 16)
writer.Write((short)(in_data[i] * 32768f));
if (bitRate == 8)
writer.Write((byte)((in_data[i] * 128f) + 128));
}
}
// Compare new wavedata with copydata
if (wavedata.SequenceEqual(copydata))
{
Console.WriteLine("Data has no changes");
}
else
{
Console.WriteLine("Data has changed!");
}
// Save modified wavedata
string targetFilePath = "sound_low.wav";
if (File.Exists(targetFilePath))
File.Delete(targetFilePath);
using (BinaryWriter writer = new BinaryWriter(File.OpenWrite(targetFilePath)))
{
writer.Write(waveheader);
writer.Write(wavedata);
}
Console.ReadLine();
}
【问题讨论】:
-
您确定您的音频文件的标题是 44 字节吗?根据此页面sonicspot.com/guide/wavefiles.html 它取决于很多东西,需要正确解析。
-
你是对的!我将自动回答我的问题以发布正确的用法。
标签: c# audio wav pitch pitch-shifting