-2

I am trying to use libsndfile to write a multichannel wav that can be read by MATLAB 2010+.

the following code writes a 4 channel interleaved wav. all samples on channel 1 should be 0.1, on channel 2 they are 0.2, on channel 3 ... etc.

Each channel is 44100 samples in length.

I drag the wave file onto the MATLAB workspace and unfortunately MATLAB keeps returning "File contains uninterpretable data".

It may also be worth noting that when all samples are set to 0.0, MATLAB successfully reads the file, although very slowly.

I have successfully used libsndfile to read multichannel data written by MATLAB's wavwrite.m, so the library is setup up correctly I believe.

Audacity can read the resulting file from the code below.

VS 2012 64 bit compiler, Win7 64bit, MATLAB 2015a

ref: the code has been adapted from http://www.labbookpages.co.uk/audio/wavFiles.html

Any suggestions, I presume i'm making a simple error here?

Thanks

#include <sndfile.h>
#include <stdio.h>
#include <stdlib.h>

int main()
{
// Create interleaved audio data
int numFrames_out = 44100;
int channels = 4;
float *int_y;   
int_y = (float*)malloc(channels*numFrames_out*sizeof(float));   
long q=0;
for (long i = 0; i<numFrames_out; i++)
{
    for (int j = 0; j<channels; j++)
    {
        int_y[q+j] = ((float)(j+1))/10.0;
    }
    q+=channels;
}


// Set multichannel file settings
SF_INFO info;
info.format = SF_FORMAT_WAV | SF_FORMAT_PCM_32;
info.channels = channels;
info.samplerate = 44100;

// Open sound file for writing
char out_filename[] = "out_audio.wav";
SNDFILE *sndFile = sf_open(out_filename, SFM_WRITE, &info);
if (sndFile == NULL) 
{
  fprintf(stderr, "Error opening sound file '%s': %s\n", out_filename, sf_strerror(sndFile));
  return -1;
}

// Write frames
long writtenFrames = sf_writef_float(sndFile, int_y, numFrames_out);

// Check correct number of frames saved
if (writtenFrames != numFrames_out) {
    fprintf(stderr, "Did not write enough frames for source\n");
    sf_close(sndFile);
    free(int_y);
    return -1;
}
sf_close (sndFile);
}
4

1 回答 1

0

看起来您只是在错误情况下关闭输出文件(使用 sf_close())。除非您在程序结束时调用 sf_close(),否则输出文件不会是格式正确的 WAV 文件。

于 2015-04-16T20:42:49.730 回答