Search code examples
c++matlabarmadillolibsndfile

Armadillo load wav file to mat


I want to read wav file into mat using Armadillo. It looks like wavread function in matlab:

[sample_data,sample_rate] = wavread('test.wav');
sample_data = sample_data(1 : sample_rate * 1.5);

Seems Armadillo doesn't support this, so I tried to use libsndfile lib:

SNDFILE     *infile = NULL ;
SF_INFO     sfinfo ;
infile = sf_open(filename, SFM_READ, &sfinfo);

int N = 1024;
double samples[N];
double sample_rate = sfinfo.samplerate;
sf_read_double(infile, samples, N);

My questions:

  1. Is this way correct? Seem I can only read fixed amount samples.
  2. How can I convert sample data to mat or vec?
  3. Is there any way to access matrix by colon range index like this matlab code: sample_data = sample_data(1 : sample_rate * 1.5); ?

Solution

    1. Yes, this way correct. If you need get all samples you can do so:

      auto sample_chanels = sfinfo.channels;
      
      std::vector<std::vector<double>> vec;
      
      std::vector<double> temp(sample_chanels);
      
      while(sf_read_double(infile, temp.data(), sample_chanels))
      vec.push_back(temp);
      
    2. For example so:

      mat m1(vec.size(),sample_chanels);
      
      for( size_t i=0;i<vec.size();i++)
         m1.row(i) = mat(vec[i]).t();
      
    3. Complete analogy was not available, but you can use std::copy (), because the mat have member functions begin()

        arma::vec D(shift);
      
        if(shift < m1.size())
          std::copy(m1.begin(),m1.begin()+shift,D.begin());
      

    Link to the complete example: http://pastebin.com/X4fgzBrR