-
Notifications
You must be signed in to change notification settings - Fork 4
/
Copy pathimperative_visualizer.pde
315 lines (237 loc) · 7.78 KB
/
imperative_visualizer.pde
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
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
// Under GNU v3.0 License
// Made by Estlin (Kassian Houben) for his 5 track EP "Imperative"
// Find it on all major platforms
import ddf.minim.*;
import ddf.minim.analysis.*;
import ddf.minim.effects.*;
import ddf.minim.signals.*;
import ddf.minim.spi.*;
import ddf.minim.ugens.*;
import com.hamoid.*;
VideoExport videoExport;
// Configuration variables
// ------------------------
int canvasWidth = 1080;
int canvasHeight = 1080;
String audioFileName = "kingfisher.mp3"; // Audio file in data folder
boolean export = false; // Either export or real time
boolean generateAudioTxtFile = false; // Will auto generate if export is true and no audio txt file exists
float fps = 30;
float smoothingFactor = 0.25; // FFT audio analysis smoothing factor
// ------------------------
// Global variables
// Export variables
String SEP = "|";
float frameDuration = 1 / fps;
BufferedReader audioReader;
String[] fftFile;
String songName;
// Real time variables
AudioPlayer track;
FFT fft;
Minim minim;
// General
int bands = 256; // must be multiple of two
float[] spectrum = new float[bands];
float[] sum = new float[bands];
// Graphics
float unit;
int groundLineY;
PVector center;
// Processing 3.0 function for setting size() with variables
void settings() {
size(canvasWidth, canvasHeight);
smooth(8);
}
void setup() {
hint(ENABLE_STROKE_PURE);
if (!export) {
frameRate(fps);
}
if (export) {
// Produce the video as fast as possible
frameRate(1000);
}
// Graphics related variable setting
unit = height / 100; // Everything else can be based around unit to make it change depending on size
strokeWeight(unit / 10.24);
groundLineY = height * 3/4;
center = new PVector(width / 2, height * 3/4);
// Set up .mp4 export
if (export) {
File tempFile = new File(dataPath(audioFileName + ".txt"));
// Make sure txt file exists
if (!tempFile.exists() || generateAudioTxtFile) {
if(!audioToTextFile(audioFileName)) {
exit();
}
}
// Now open the text file we just created for reading
audioReader = createReader(audioFileName + ".txt");
// Set up the video exporting
videoExport = new VideoExport(this);
videoExport.setFrameRate(fps);
try {
videoExport.setAudioFileName(audioFileName);
}
catch (Exception e){
println("Could not set video export audio file");
}
videoExport.startMovie();
}
else { // Real time
minim = new Minim(this);
track = minim.loadFile(audioFileName, 2048);
track.loop();
fft = new FFT( track.bufferSize(), track.sampleRate() );
fft.linAverages(bands);
// track.cue(60000); // Cue in miliseconds
}
}
void draw() {
// If exporting to mp4
if (export) {
String line;
try {
line = audioReader.readLine(); // Reads txt file line by line
}
catch (IOException e) {
e.printStackTrace();
line = null;
}
if (line == null) {
// Done reading the file.
// Close the video file.
if (export) {
videoExport.endMovie();
}
exit();
} else {
if (export) { // remove first frame from visualizer
if (frameCount == 1) {
return;
}
}
String[] p = split(line, SEP);
float soundTime = float(p[0]);
//println("Current export time: " + videoExport.getCurrentTime());
//println("Sound time: " + soundTime);
while (videoExport.getCurrentTime() < soundTime + frameDuration * 10) { // frameDuration * delay -- need to experiment
spectrum = new float[bands];
// Iterate over all our data points (different
for (int i=1; i<p.length; i += 2) { // Iterate through pairs of L/R
spectrum[((i + 1) / 2) - 1] = (float(p[i]) + float(p[i + 1])) / 2; // Average of left right and add to spectrum
// Smooth the FFT spectrum data by smoothing factor
sum[((i + 1) / 2) - 1] += (abs(spectrum[((i + 1) / 2) - 1]) - sum[((i + 1) / 2) - 1]) * smoothingFactor;
}
// Reset canvas
fill(0);
noStroke();
rect(0, 0, width, height);
noFill();
drawAll(sum);
if (export) {
videoExport.saveFrame();
}
}
}
}
else { // Real time
fft.forward( track.mix );
spectrum = new float[bands];
for(int i = 0; i < fft.avgSize(); i++)
{
spectrum[i] = fft.getAvg(i) / 2 + fft.getAvg(i) / 2; // Average of left right and add to spectrum
// Smooth the FFT spectrum data by smoothing factor
sum[i] += (abs(spectrum[i]) - sum[i]) * smoothingFactor;
}
// Reset canvas
fill(0);
noStroke();
rect(0, 0, width, height);
noFill();
drawAll(sum);
}
}
// Get the Y position at position X of ground sine wave
float getGroundY(float groundX) {
float angle = 1.1 * groundX / unit * 10.24;
float groundY = sin(radians(angle + frameCount * 2)) * unit * 1.25 + groundLineY - unit * 1.25;
return groundY;
}
// Does circle contain point
boolean circleContains(PVector position, PVector center, float radius) {
// If distance between center and point is less than radius, then circle contains
if (dist(position.x, position.y, center.x, center.y) < radius) {
return true;
}
return false;
}
// Minim based audio FFT to data text file conversion.
boolean audioToTextFile(String fileName) {
PrintWriter output;
Minim minim = new Minim(this);
output = createWriter(dataPath(fileName + ".txt"));
AudioSample track;
try {
track = minim.loadSample(fileName, 2048);
}
catch (Exception e) {
println("Error: " + e);
println("Could not get audio file titled: " + fileName);
return false;
}
int fftSize = 1024;
float sampleRate = track.sampleRate();
float[] fftSamplesL = new float[fftSize];
float[] fftSamplesR = new float[fftSize];
float[] samplesL = track.getChannel(AudioSample.LEFT);
float[] samplesR = track.getChannel(AudioSample.RIGHT);
FFT fftL = new FFT(fftSize, sampleRate);
FFT fftR = new FFT(fftSize, sampleRate);
//fftL.logAverages(86, 1);
//fftR.logAverages(86, 1);
fftL.linAverages(bands);
fftR.linAverages(bands);
int totalChunks = (samplesL.length / fftSize) + 1;
int fftSlices = fftL.avgSize();
for (int ci = 0; ci < totalChunks; ++ci) {
int chunkStartIndex = ci * fftSize;
int chunkSize = min( samplesL.length - chunkStartIndex, fftSize );
System.arraycopy( samplesL, chunkStartIndex, fftSamplesL, 0, chunkSize);
System.arraycopy( samplesR, chunkStartIndex, fftSamplesR, 0, chunkSize);
if ( chunkSize < fftSize ) {
java.util.Arrays.fill( fftSamplesL, chunkSize, fftSamplesL.length - 1, 0.0 );
java.util.Arrays.fill( fftSamplesR, chunkSize, fftSamplesR.length - 1, 0.0 );
}
fftL.forward( fftSamplesL );
fftR.forward( fftSamplesL );
// The format of the saved txt file.
// The file contains many rows. Each row looks like this:
// T|L|R|L|R|L|R|... etc
// where T is the time in seconds
// Then we alternate left and right channel FFT values
// The first L and R values in each row are low frequencies (bass)
// and they go towards high frequency as we advance towards
// the end of the line.
StringBuilder msg = new StringBuilder(nf(chunkStartIndex/sampleRate, 0, 3).replace(',', '.'));
for (int i=0; i<fftSlices; ++i) {
msg.append(SEP + nf(fftL.getAvg(i), 0, 4).replace(',', '.'));
msg.append(SEP + nf(fftR.getAvg(i), 0, 4).replace(',', '.'));
}
output.println(msg.toString());
}
track.close();
output.flush();
output.close();
println("Sound analysis done");
return true;
}
void keyPressed() {
if (key == 'q') {
if (export) {
videoExport.endMovie();
}
exit();
}
}