Encoding.ASCII.GetBytes Matlab问题

时间:2013-12-20 16:01:56

标签: c# matlab ascii wav

WriteWavHeader函数实现WAV标头。问题是当我尝试用wavread在Matlab中读取WAV文件时,我失败了。通过在wavread中添加断点,我已经检查过,尽管Matlab读取'WAVE','fmt'和'data'标题很好(即ck.ID等于'WAVE' ,在每次迭代中分别为'fmt ''data',它无法正确读取'end of file'字符串。具体来说,ck.ID等于一堆奇怪的ASCII字符。当我硬编码ck.ID = 'end of file'时,我设法读取wav文件。关于如何解决这个问题的任何想法?

static void WriteWavHeader(Stream stream, int dataLength)
    {
        using (var memStream = new MemoryStream(64))
        {
            int cbFormat = 18; //sizeof(WAVEFORMATEX)

            WAVEFORMATEX format = new WAVEFORMATEX()
            {
                wFormatTag = 1,
                nChannels = 1,
                nSamplesPerSec = 16000,
                nAvgBytesPerSec = 32000,
                nBlockAlign = 2,
                wBitsPerSample = 16,
                cbSize = 0
            };

            using (var binarywriter = new BinaryWriter(memStream))
            {
                //RIFF header
                WriteString(memStream, "RIFF");
                binarywriter.Write(dataLength + 8 + cbFormat + 8 + 4); //File size - 8

                WriteString(memStream, "WAVE");
                WriteString(memStream, "fmt ");
                binarywriter.Write(cbFormat);

                //WAVEFORMATEX
                binarywriter.Write(format.wFormatTag);
                binarywriter.Write(format.nChannels);
                binarywriter.Write(format.nSamplesPerSec);
                binarywriter.Write(format.nAvgBytesPerSec);
                binarywriter.Write(format.nBlockAlign);
                binarywriter.Write(format.wBitsPerSample);
                binarywriter.Write(format.cbSize);

                //data header
                WriteString(memStream, "data");
                binarywriter.Write(dataLength);

                memStream.WriteTo(stream);
                WriteString(memStream, "end of file");

            }
        }
    }

static void WriteString(Stream stream, string s)
    {
        byte[] bytes = Encoding.ASCII.GetBytes(s);
        stream.Write(bytes, 0, bytes.Length);

    }

1 个答案:

答案 0 :(得分:0)

您是否正在查看此位代码(edit wavread位于第208行?)

function [ck,msg] = read_ckinfo(fid)

msg     = '';
ck.fid  = fid;
ck.Data = [];
err_msg = getString(message('MATLAB:audiovideo:wavread:TruncatedChunkHeader'));

[s,cnt] = fread(fid,4,'char');

% Do not error-out if a few (<4) trailing chars are in file
% Just return quickly:
if (cnt~=4),
    if feof(fid),
        % End of the file (not an error)
        ck.ID = 'end of file';  % unambiguous chunk ID (>4 chars)
        ck.Size = 0;
    else
        msg = err_msg;
    end
    return
end
...

据我所知,没有有效的ID /块称为“文件结束”(它也不是四个字符长)。此函数只是将'end of file'字符串作为标志返回到find_cktype函数(参见第76和99行)。换句话说,您似乎正在将一串数据(您的“奇怪的ASCII字符”)写入您的WAV文件:

WriteString(memStream, "end of file");

在Matlab中检查文件结尾的方法是使用feof或检查fread返回的输出的长度。

如果你想阅读WAV,我想你会写一些与你的标题所说的匹配的实际WAV数据。