Created
December 5, 2010 18:11
-
-
Save jacobjoaquin/729308 to your computer and use it in GitHub Desktop.
Uses a buffer for writing audio to an aiff file.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* simple_buffer.c | |
* Jacob Joaquin <jacobjoaquin@gmail.com> | |
* csoundblog.com | |
* | |
* Uses a buffer for writing audio to an aiff file. | |
* (error handling not included) | |
* | |
* License: | |
* GNU Lesser General Public License | |
* http:/*www.gnu.org/copyleft/lesser.html | |
* | |
* libsndfile by Erik de Castro Lopo | |
* http:/*www.mega-nerd.com/libsndfile/ | |
*/ | |
#include <math.h> | |
#include <sndfile.h> | |
#include <stdlib.h> | |
const float two_pi = 6.2831853071795862; | |
int main() | |
{ | |
SNDFILE* sndfile; /* sound file */ | |
SF_INFO* sf_info; /* file properties */ | |
int sample_rate = 44100; /* Sample rate */ | |
int block_size = 100; /* Block size */ | |
int channels = 1; /* Mono */ | |
int nblocks = (sample_rate / block_size) * 4.0; /* 4 seconds */ | |
float* frames_buffer; /* Audio output buffer */ | |
int frames_buffer_size; /* Length of buffer */ | |
float sine_out = 0.0; /* Oscillator value */ | |
float sine_phase = 0.0; /* Oscillator phase */ | |
float sine_inc = (1.0 / sample_rate) * 440.0; /* Oscillator A 440 */ | |
/* Set sound file properties */ | |
sf_info = (SF_INFO *) malloc(sizeof(SF_INFO)); | |
sf_info->samplerate = sample_rate; | |
sf_info->channels = channels; | |
sf_info->format = SF_FORMAT_AIFF | SF_FORMAT_PCM_16; | |
/* Open sound file for writing */ | |
sndfile = sf_open("./simple_buffer.aif", SFM_WRITE, sf_info); | |
/* Intialize frames_buffer */ | |
frames_buffer = (float*) malloc(channels * sizeof(float) * nblocks); | |
frames_buffer_size = block_size * channels; | |
/* Main audio loop */ | |
do | |
{ | |
float* frame_ptr = frames_buffer; /* Current frame */ | |
int frames = block_size; /* Frames per block */ | |
/* Process audio block */ | |
do | |
{ | |
/* Sine A 440 -3dB */ | |
sine_out = sin(sine_phase * two_pi) * 0.707; | |
sine_phase += sine_inc; | |
if (sine_phase >= 1.0) | |
{ | |
sine_phase -= 1.0; | |
} | |
/* Write sample to audio buffer */ | |
*frame_ptr++ = sine_out; | |
} while (--frames); | |
/* Write audio buffer to sound file */ | |
sf_writef_float(sndfile, frames_buffer, frames_buffer_size); | |
} while (--nblocks); | |
/* Clean up and return */ | |
free(frames_buffer); | |
sf_close(sndfile); | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment