如何将一个WAV音频文件插入到另一个WAV文件中?

时间:2019-05-29 13:51:41

标签: c# xamarin xamarin.forms wav

我正在研究xamarin。我开发了一个应用程序,可以记录用户的声音。现在,我希望该用户可以再次将其插入已记录的文件中。我的意思是,如果用户录制了10分钟的交易记录,现在他想在6分钟后插入更多内容,那么他​​应该能够做到。我尝试了一些例子,但没有成功。当我插入一段时间后,有时插入后的内容会损坏。

以下是我已实现的代码。它工作了一段时间,插入的内容损坏了一段时间。

     string[] files = new string[] { originalFile, insertFile };
        if (!files[0].Contains("tempfile_") && files.Length > 1)
        {
            if (File.Exists(files[0]))
            {
                string newPath = files[1].Replace("tempfile_1", 
     "tempfile_0");
                MoveExistingFile(files[0], newPath);
                files[0] = newPath;
            }
            else
            {
                files = files.Skip(1).ToArray();
            }
        }

        var duration = DependencyService.Get<IPlayService> 
    ().GetDuration(files[0]);
        var bufferTime = Math.Round(duration);

        FileStream originalStream = new FileStream(files[0], 
        FileMode.Open, FileAccess.Read);
        byte[] originalByteArray = new byte[originalStream.Length - 44];

        var perSecondLength = originalByteArray.Length / (int)bufferTime;
        var splitIndex = (perSecondLength * SplitSecond);

        var byteArray1 = new byte[(splitIndex)];
        var byteArray2 = new byte[originalByteArray.Length - splitIndex];

        FileStream insertStream = new FileStream(files[1], FileMode.Open, 
        FileAccess.Read);
        byte[] insertByteArray = new byte[insertStream.Length - 44];
        var byteArray3 = new byte[insertByteArray.Length];

        originalStream.Position = 44;
        originalStream.Read(byteArray1, 0, byteArray1.Length);
        originalStream.Position = byteArray1.Length;
        originalStream.Read(byteArray2, 0, byteArray2.Length);
        originalStream.Close();

        insertStream.Position = 44;
        insertStream.Read(byteArray3, 0, byteArray3.Length);
        insertStream.Close();

        WaveIO wa_IN = new WaveIO();
        WaveIO wa_out = new WaveIO();

        wa_out.DataLength = 0;
        wa_out.length = 0;

        //Gather header data
        foreach (string path in files)
        {
            wa_IN.WaveHeaderIN(@path);
            wa_out.DataLength += wa_IN.DataLength;
            wa_out.length += wa_IN.length;
        }

        //Recontruct new header
        wa_out.BitsPerSample = wa_IN.BitsPerSample;
        wa_out.channels = wa_IN.channels;
        wa_out.samplerate = wa_IN.samplerate;
        wa_out.WaveHeaderOUT(@outfile);

        FileStream fo = new FileStream(@outfile, FileMode.Append, 
        FileAccess.Write);
        BinaryWriter bw = new BinaryWriter(fo);
        bw.Write(byteArray1);
        bw.Write(byteArray3);
        bw.Write(byteArray2);
        bw.Close();
        fo.Close();

0 个答案:

没有答案