William Clark
William Clark

Reputation: 65

libsndfile cannot encode WAV with float array

I'm trying to write a file using libsndfile in C++, with an array of floats:

 void encode_file (const char *outfilename, int filetype)
  { 
    static float buffer [BUFFER_LEN] ;
    for (int i = 0; i< BUFFER_LEN; i++) {
      buffer[i] = (float)(write_file_buffer.get()[i]);
    }
    
    SNDFILE     *outfile ;
    SF_INFO     sfinfo ;
    int         k, readcount ;
    
    printf ("    %s ", outfilename) ;
    fflush (stdout) ;

    k = 16 - strlen (outfilename) ;
    //PUT_DOTS (k) ;

    sfinfo.format = filetype ;
    if (! sf_format_check (&sfinfo))
    {
        printf ("Invalid encoding\n") ;
        return ;
    } ;
    
    if (! (outfile = sf_open (outfilename, SFM_WRITE, &sfinfo)))  // It fails here
    {   printf ("Error : could not open file : %s\n", outfilename) ;
        puts (sf_strerror (NULL)) ;
        _exit (1) ;
    };
        
    
    sf_write_float (outfile, buffer, BUFFER_LEN) ;  // this won't run anyways if I remove the check above

    
    sf_close (outfile) ;

    printf ("ok\n") ;

    return ;            
}

encode_file is being called like this:

encode_file(c,   SF_FORMAT_WAV | SF_FORMAT_PCM_16); // c is a char *, that part is fine

write_file_buffer had previously been filled with doubles (but that shouln't matter due to the conversion above):

write_file_buffer[i] = ((double)(data[i]) - 32767.0)/32767.0;

The error I get of course is "pcmu000.wav Invalid encoding"

But I'm using the same code basically as when I was following this example: https://vroby.ddns.net/Public/sdlBasic/MinGW/sorgenti/audacity/audacity-src-1.2.2/lib-src/libsndfile/examples/generate.c And that worked just fine. I'm not clear on what I'm doing wrong since I'm passing in the same encoding as one used in the the working example (SF_FORMAT_WAV | SF_FORMAT_PCM_16).

Any advice would be much appreciated, I've been stuck on this for a minute and am mostly just scratching my head at this point.

Perhaps it expects stereo, or some other info to be loaded in the buffer (it's mono, basically an array of lot of sequential floats between -1.0 and 1.0)?

Upvotes: 0

Views: 465

Answers (1)

William Clark
William Clark

Reputation: 65

user253751 above got it: SF_INFO needs more of its parameters initialized. This was solved by going into the encode_file function and adding these lines right around the setting of sf_info.format:

    sfinfo.channels = 1;
    sfinfo.samplerate = 44100;

Thanks user253751!

Upvotes: 1

Related Questions