我正在读取原始音频文件(CD track rip),进行字节交换,然后写回wav文件。
我正常处理字节的例程,但只有大约一半的文件。我是一个VB.NET开发人员,不是真正的C#开发人员,而且这段代码没有正确转换为VB.NET(它出现溢出错误)。
它实际上不是一个“交换”,而是一个计算/修剪。 (短)((缓冲[i + 1] * 256)+缓冲[i])
我相信它只写了一半样本,但我不知道如何修复!
public static short[] SwapBytesArray(string fileName)
{
byte[] buffer = System.IO.File.ReadAllBytes(fileName);
long fileLength = buffer.LongLength;
if ((fileLength & 1) == 1)
{
throw new ArgumentException("File length must be an even number of bytes");
}
System.Collections.Generic.List<short> sList = new System.Collections.Generic.List<short>();
for (long i = 0; i < fileLength - 1; i += 2)
{
byte tmp = buffer[i];
sList.Add((short)((buffer[i + 1] * 256) + buffer[i]));
//buffer[i + 1] = tmp;
}
return sList.ToArray();
}
答案 0 :(得分:1)
如果文件的大小大于最大整数,那么你将溢出索引变量(索引应该很长,因为num是long)。大概你使用buffer.LongLength而不是buffer.Length,因为你知道你的数据更大,所以无论如何都是一个可能的问题。
答案 1 :(得分:1)
为什么要返回short
的数组?
如果要写回文件,byte[]
数组不是更好的选择吗?
即
public static byte[] SwapBytes(string fileName)
{
byte[] buffer = System.IO.File.ReadAllBytes(fileName);
long fileLength = buffer.LongLength;
if ((fileLength & 1) == 1)
{
throw new ArgumentException("File length must be an even number of bytes");
}
for (long i = 0; i < fileLength - 1 ; i +=2 )
{
byte tmp = buffer[i];
buffer[i] = buffer[i + 1];
buffer[i + 1] = tmp;
}
return buffer;
}
答案 2 :(得分:1)
这看起来非常浪费内存。您将整个文件作为一个字节序列读入,然后在short[]
数组中复制它。当你返回那个数组时,你甚至可以再次复制它。
您的实际问题可能在于此函数返回时写出短路的方式(而不是字节)。我想我们需要看到那段代码。
答案 3 :(得分:1)
我认为流媒体方法会更高效,更不容易出错。 .NET对流有很好的支持,所以类似下面这样的东西应该可以工作:
public void SwapBytesStreamed(Stream inputStream, Stream outputStream)
{
byte[] bytePair = new byte[2];
long offset = 0;
while (offset < inputStream.Length)
{
int bytesRead = inputStream.Read(bytePair, 0, 2);
if (bytesRead == 0) break;
if (bytesRead == 2)
{
outputStream.WriteByte(bytePair[1]);
}
outputStream.WriteByte(bytePair[0]);
offset += bytesRead;
}
}
然后使用它如下:
public Stream SwapBytesInFile(string filename)
{
Stream inputStream = File.Open(filename, FileMode.Open);
MemoryStream outputStream = new MemoryStream();
SwapBytesStreamed(inputStream, outputStream);
}