Keypress to WAV file playback
This scripts needs to be run in a terminal because it requires you to interact with Bela using your computer's keyboard. Note that it CAN NOT be run from within the IDE or the IDE's console.
See here how to use Bela with a terminal.
This program shows how to playback audio samples from a buffer using key strokes.
An audio file is loaded into a vector data
. This is accessed with a read pointer that is incremented at audio rate within the render function: out += data[gReadPtr++]
.
Note that the read pointer is stopped from incrementing past the length of the data
. This is achieved by comparing the read pointer value against the sample length which we can access as follows: data.size()
.
You can trigger the sample with keyboard input:
'a' <enter> to start playing the sample
's' <enter> to stop
'q' <enter> or ctrl-C to quit
Monitoring of the keyboard input is done in a low priority task to avoid interfering with the audio processing.
#include <sys/types.h>
#include <libraries/AudioFile/AudioFile.h>
#include <string>
#include <vector>
std::string fileName;
int gReadPtr;
std::vector<float> data;
bool initialise_trigger();
void trigger_samples(void*);
{
fileName = (const char *)userData;
if(0 == data.size()) {
fprintf(stderr, "Unable to load file\n");
return false;
}
gReadPtr = -1;
if(initialise_trigger() == false)
return false;
return true;
}
{
for(
unsigned int n = 0; n < context->
audioFrames; n++) {
float out = 0;
if(gReadPtr != -1)
out += data[gReadPtr++];
if(gReadPtr >= data.size())
gReadPtr = -1;
}
}
bool initialise_trigger()
{
return false;
rt_printf("Press 'a' <enter> to trigger sample,\n"
" 's' <enter> to stop the current playing sample\n"
" 'q' <enter> or ctrl-C to quit\n");
return true;
}
void trigger_samples(void*)
{
char keyStroke = '.';
fd_set readfds;
struct timeval tv;
int fd_stdin;
fd_stdin = fileno(stdin);
FD_ZERO(&readfds);
FD_SET(fileno(stdin), &readfds);
tv.tv_sec = 0;
tv.tv_usec = 1000;
fflush(stdout);
int num_readable = select(fd_stdin + 1, &readfds, NULL, NULL, &tv);
if(num_readable > 0){
scanf("%c", &keyStroke);
if(keyStroke != '\n'){
switch (keyStroke)
{
case 'a':
gReadPtr = 0;
break;
case 's':
gReadPtr = -1;
break;
case 'q':
break;
default:
break;
}
}
}
usleep(1000);
}
}
{
}