繁体   English   中英

以特定的偏移量插入十六进制数据

[英]insert hex data at specific offset

我需要能够将音频数据插入现有的ac3文件中。 AC3文件非常简单,可以相互附加而不会剥离标头或其他任何内容。 我的问题是,如果要添加/覆盖/擦除一个ac3文件的大块,则必须以32ms为增量进行操作,每个32ms等于1536个字节的数据。 因此,当我插入一个数据块(必须为1536字节,正如我刚才所说的)时,我需要找到可以被1536整除的最近偏移量(如0、1536(0x600),3072(0xC00)等)。 假设我能弄清楚。 我已经读过有关在特定偏移量处更改特定字符的信息,但是我需要插入(而不是覆盖)整个1536字节的数据块。 给定起始偏移量和1536字节的数据块,我将如何在C#中执行此操作?

编辑:我要插入的数据块基本上只有32ms的静默时间,而我具有它的十六进制,ASCII和ANSI文本转换。 当然,我可能想多次插入此块以获得128ms的静音,而不仅仅是32ms。

byte[] filbyte=File.ReadAllBytes(@"C:\abc.ac3");
byte[] tobeinserted=;//allocate in your way using encoding whatever

byte[] total=new byte[filebyte.Length+tobeinserted.Length];

for(int i=0;int j=0;i<total.Length;)
{
   if(i==1536*pos)//make pos your choice
   { 
     while(j<tobeinserted.Length) 
       total[i++]=tobeinserted[j++];
   }
   else{total[i++]=filbyte[i-j];}
}

File.WriteAllBytes(@"C:\abc.ac3",total);

这是可以满足您需要的帮助方法:

public static void Insert(string filepath, int insertOffset, Stream dataToInsert)
{
    var newFilePath = filepath + ".tmp";
    using (var source = File.OpenRead(filepath))
    using (var destination = File.OpenWrite(newFilePath))
    {
        CopyTo(source, destination, insertOffset);// first copy the data before insert
        dataToInsert.CopyTo(destination);// write data that needs to be inserted:
        CopyTo(source, destination, (int)(source.Length - insertOffset)); // copy remaining data
    }

    // delete old file and rename new one:
    File.Delete(filepath);
    File.Move(newFilePath, filepath);
}

private static void CopyTo(Stream source, Stream destination, int count)
{
    const int bufferSize = 32 * 1024;
    var buffer = new byte[bufferSize];

    var remaining = count;
    while (remaining > 0)
    {
        var toCopy = remaining > bufferSize ? bufferSize : remaining;
        var actualRead = source.Read(buffer, 0, toCopy);

        destination.Write(buffer, 0, actualRead);
        remaining -= actualRead;
    }
}

这里是一个NUnit测试与用法示例:

[Test]
public void TestInsert()
{
    var originalString = "some original text";
    var insertString = "_ INSERTED TEXT _";
    var insertOffset = 8;

    var file = @"c:\someTextFile.txt";

    if (File.Exists(file))
        File.Delete(file);

    using (var originalData = new MemoryStream(Encoding.ASCII.GetBytes(originalString)))
    using (var f = File.OpenWrite(file))
        originalData.CopyTo(f);

    using (var dataToInsert = new MemoryStream(Encoding.ASCII.GetBytes(insertString)))
        Insert(file, insertOffset, dataToInsert);

    var expectedText = originalString.Insert(insertOffset, insertString);

    var actualText = File.ReadAllText(file);
    Assert.That(actualText, Is.EqualTo(expectedText));
}

请注意,我已经删除了一些代码清晰度检查-不要忘记检查null,文件访问权限和文件大小。 例如, insertOffset可以大于文件长度-在此不检查此条件。

暂无
暂无

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

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