Bela
Real-time, ultra-low-latency audio and sensor processing system for BeagleBone Black
 All Classes Files Functions Variables Typedefs Macros Groups
SampleLoader.h
1 /***** SampleLoader.h *****/
2 
3 #include <Bela.h>
4 #include <libraries/sndfile/sndfile.h> // to load audio files
5 #include <string>
6 #include <iostream>
7 #include <cstdlib>
8 
9 using namespace std;
10 
11 // Load samples from file
12 int getSamples(string file, float *buf, int channel, int startFrame, int endFrame)
13 {
14  SNDFILE *sndfile ;
15  SF_INFO sfinfo ;
16  sfinfo.format = 0;
17  if (!(sndfile = sf_open (file.c_str(), SFM_READ, &sfinfo))) {
18  cout << "Couldn't open file " << file << ": " << sf_strerror(sndfile) << endl;
19  return 1;
20  }
21 
22  int numChannelsInFile = sfinfo.channels;
23  if(numChannelsInFile < channel+1)
24  {
25  cout << "Error: " << file << " doesn't contain requested channel" << endl;
26  return 1;
27  }
28 
29  int frameLen = endFrame-startFrame;
30 
31  if(frameLen <= 0 || startFrame < 0 || endFrame <= 0 || endFrame > sfinfo.frames)
32  {
33  cout << "Error: " << file << " invalid frame range requested" << endl;
34  return 1;
35  }
36 
37  sf_seek(sndfile,startFrame,SEEK_SET);
38 
39  float* tempBuf = new float[frameLen*numChannelsInFile];
40 
41  int readcount = sf_read_float(sndfile, tempBuf, frameLen*numChannelsInFile); //FIXME
42 
43  // Pad with zeros in case we couldn't read whole file
44  for(int k = readcount; k <frameLen*numChannelsInFile; k++)
45  tempBuf[k] = 0;
46 
47  for(int n=0;n<frameLen;n++)
48  buf[n] = tempBuf[n*numChannelsInFile+channel];
49  delete[] tempBuf;
50 
51  sf_close(sndfile);
52 
53  return 0;
54 }
55 
56 int getNumChannels(string file) {
57 
58  SNDFILE *sndfile ;
59  SF_INFO sfinfo ;
60  sfinfo.format = 0;
61  if (!(sndfile = sf_open (file.c_str(), SFM_READ, &sfinfo))) {
62  cout << "Couldn't open file " << file << ": " << sf_strerror(sndfile) << endl;
63  return -1;
64  }
65 
66  return sfinfo.channels;
67 }
68 
69 int getNumFrames(string file) {
70 
71  SNDFILE *sndfile ;
72  SF_INFO sfinfo ;
73  sfinfo.format = 0;
74  if (!(sndfile = sf_open (file.c_str(), SFM_READ, &sfinfo))) {
75  cout << "Couldn't open file " << file << ": " << sf_strerror(sndfile) << endl;
76  return -1;
77  }
78 
79  return sfinfo.frames;
80 }
81 
Main Bela public API.