-
Notifications
You must be signed in to change notification settings - Fork 0
/
SampleLoader.h
100 lines (76 loc) · 2.52 KB
/
SampleLoader.h
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
/***** SampleLoader.h *****/
// Built upon and inspired by:
// - http://docs.bela.io/Audio_2sample-loader_2SampleLoader_8h_source.html
#include <Bela.h>
#include <libraries/sndfile/sndfile.h> // to load audio files
#include <string>
#include <iostream>
#include <cstdlib>
using namespace std;
// Load samples from file
int getSamples(string file, float *buf, int channel, int startFrame, int endFrame)
{
SNDFILE *sndfile ;
SF_INFO sfinfo ;
sfinfo.format = 0;
if (!(sndfile = sf_open (file.c_str(), SFM_READ, &sfinfo))) {
cout << "Couldn't open file " << file << ": " << sf_strerror(sndfile) << endl;
return 1;
}
int numChannelsInFile = sfinfo.channels;
if(numChannelsInFile < channel+1)
{
cout << "Error: " << file << " doesn't contain requested channel" << endl;
return 1;
}
int frameLen = endFrame-startFrame;
if(frameLen <= 0 || startFrame < 0 || endFrame <= 0 || endFrame > sfinfo.frames)
{
//printf("framelen %d startframe %d endframe %d, sfinfo.frames %d\n",frameLen,startFrame,endFrame,sfinfo.frames);
cout << "Error: " << file << " invalid frame range requested" << endl;
return 1;
}
sf_seek(sndfile,startFrame,SEEK_SET);
float* tempBuf = new float[frameLen*numChannelsInFile];
int subformat = sfinfo.format & SF_FORMAT_SUBMASK;
int readcount = sf_read_float(sndfile, tempBuf, frameLen*numChannelsInFile); //FIXME
// Pad with zeros in case we couldn't read whole file
for(int k = readcount; k <frameLen*numChannelsInFile; k++)
tempBuf[k] = 0;
if (subformat == SF_FORMAT_FLOAT || subformat == SF_FORMAT_DOUBLE) {
double scale ;
int m ;
sf_command (sndfile, SFC_CALC_SIGNAL_MAX, &scale, sizeof (scale)) ;
if (scale < 1e-10)
scale = 1.0 ;
else
scale = 32700.0 / scale ;
cout << "File samples scale = " << scale << endl;
for (m = 0; m < frameLen; m++)
tempBuf[m] *= scale;
}
for(int n=0;n<frameLen;n++)
buf[n] = tempBuf[n*numChannelsInFile+channel];
sf_close(sndfile);
return 0;
}
int getNumChannels(string file) {
SNDFILE *sndfile ;
SF_INFO sfinfo ;
sfinfo.format = 0;
if (!(sndfile = sf_open (file.c_str(), SFM_READ, &sfinfo))) {
cout << "Couldn't open file " << file << ": " << sf_strerror(sndfile) << endl;
return -1;
}
return sfinfo.channels;
}
int getNumFrames(string file) {
SNDFILE *sndfile ;
SF_INFO sfinfo ;
sfinfo.format = 0;
if (!(sndfile = sf_open (file.c_str(), SFM_READ, &sfinfo))) {
cout << "Couldn't open file " << file << ": " << sf_strerror(sndfile) << endl;
return -1;
}
return sfinfo.frames;
}