Skip to content

Instantly share code, notes, and snippets.

@0b5vr
Created June 7, 2015 03:54
Show Gist options
  • Save 0b5vr/099731a9381792cb9adb to your computer and use it in GitHub Desktop.
Save 0b5vr/099731a9381792cb9adb to your computer and use it in GitHub Desktop.
Processing wav generator
final int SIZE = 44100;
final int RATE = 44100;
byte[] file = new byte[ 44+SIZE*4 ];
float wave( float _time, float _right ){
return sin( _time * PI * 2.0 * 440.0 );
}
void setup(){
// "RIFF"
file[ 0 ] = 'R';
file[ 1 ] = 'I';
file[ 2 ] = 'F';
file[ 3 ] = 'F';
// filesize - 8
file[ 4 ] = byte( 36+SIZE*4 );
file[ 5 ] = byte( ( 36+SIZE*4 ) >>> 8 );
file[ 6 ] = byte( ( 36+SIZE*4 ) >>> 16 );
file[ 7 ] = byte( ( 36+SIZE*4 ) >>> 24 );
// "WAVE"
file[ 8 ] = 'W';
file[ 9 ] = 'A';
file[ 10 ] = 'V';
file[ 11 ] = 'E';
// "fmt "
file[ 12 ] = 'f';
file[ 13 ] = 'm';
file[ 14 ] = 't';
file[ 15 ] = ' ';
// chunk bytes
file[ 16 ] = 16;
file[ 17 ] = 0;
file[ 18 ] = 0;
file[ 19 ] = 0;
// format ID
file[ 20 ] = 1;
file[ 21 ] = 0;
// channel
file[ 22 ] = 2;
file[ 23 ] = 0;
// sampling rate
file[ 24 ] = byte( RATE );
file[ 25 ] = byte( RATE >>> 8 );
file[ 26 ] = byte( RATE >>> 16 );
file[ 27 ] = byte( RATE >>> 24 );
// byte / sec
file[ 28 ] = byte( ( RATE*4 ) );
file[ 29 ] = byte( ( RATE*4 ) >>> 8 );
file[ 30 ] = byte( ( RATE*4 ) >>> 16 );
file[ 31 ] = byte( ( RATE*4 ) >>> 24 );
// block size
file[ 32 ] = 4;
file[ 33 ] = 0;
// bit / sample
file[ 34 ] = 16;
file[ 35 ] = 0;
// "data"
file[ 36 ] = 'd';
file[ 37 ] = 'a';
file[ 38 ] = 't';
file[ 39 ] = 'a';
// SIZE
file[ 40 ] = byte( SIZE*4 );
file[ 41 ] = byte( SIZE*4 >>> 8 );
file[ 42 ] = byte( SIZE*4 >>> 16 );
file[ 43 ] = byte( SIZE*4 >>> 24 );
for( int t=0; t<SIZE; t++ ){
int l = int( min( max( wave( t / 44100.0, 0.0 ), -1.0 ), 1.0 ) * 32768.0 );
file[ 44+t*4 ] = byte( l );
file[ 44+t*4+1 ] = byte( l >>> 8 );
int r = int( min( max( wave( t / 44100.0, 1.0 ), -1.0 ), 1.0 ) * 32768.0 );
file[ 44+t*4+2 ] = byte( r );
file[ 44+t*4+3 ] = byte( r >>> 8 );
}
saveBytes( "out.wav", file );
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment