static void float_norm_test (const char *filename) { SNDFILE *file ; SF_INFO sfinfo ; unsigned int k ; print_test_name ("float_norm_test", filename) ; sfinfo.samplerate = 44100 ; sfinfo.format = (SF_FORMAT_RAW | SF_FORMAT_PCM_16) ; sfinfo.channels = 1 ; sfinfo.frames = BUFFER_LEN ; /* Create float_data with all values being less than 1.0. */ for (k = 0 ; k < BUFFER_LEN / 2 ; k++) float_data [k] = (k + 5) / (2.0 * BUFFER_LEN) ; for (k = BUFFER_LEN / 2 ; k < BUFFER_LEN ; k++) float_data [k] = (k + 5) ; if (! (file = sf_open (filename, SFM_WRITE, &sfinfo))) { printf ("Line %d: sf_open_write failed with error : ", __LINE__) ; fflush (stdout) ; puts (sf_strerror (NULL)) ; exit (1) ; } ; /* Normalisation is on by default so no need to do anything here. */ if ((k = sf_write_float (file, float_data, BUFFER_LEN / 2)) != BUFFER_LEN / 2) { printf ("Line %d: sf_write_float failed with short write (%d ->%d)\n", __LINE__, BUFFER_LEN, k) ; exit (1) ; } ; /* Turn normalisation off. */ sf_command (file, SFC_SET_NORM_FLOAT, NULL, SF_FALSE) ; if ((k = sf_write_float (file, float_data + BUFFER_LEN / 2, BUFFER_LEN / 2)) != BUFFER_LEN / 2) { printf ("Line %d: sf_write_float failed with short write (%d ->%d)\n", __LINE__, BUFFER_LEN, k) ; exit (1) ; } ; sf_close (file) ; /* sfinfo struct should still contain correct data. */ if (! (file = sf_open (filename, SFM_READ, &sfinfo))) { printf ("Line %d: sf_open_read failed with error : ", __LINE__) ; fflush (stdout) ; puts (sf_strerror (NULL)) ; exit (1) ; } ; if (sfinfo.format != (SF_FORMAT_RAW | SF_FORMAT_PCM_16)) { printf ("Line %d: Returned format incorrect (0x%08X => 0x%08X).\n", __LINE__, (SF_FORMAT_RAW | SF_FORMAT_PCM_16), sfinfo.format) ; exit (1) ; } ; if (sfinfo.frames != BUFFER_LEN) { printf ("\n\nLine %d: Incorrect number of.frames in file. (%d => %ld)\n", __LINE__, BUFFER_LEN, SF_COUNT_TO_LONG (sfinfo.frames)) ; exit (1) ; } ; if (sfinfo.channels != 1) { printf ("Line %d: Incorrect number of channels in file.\n", __LINE__) ; exit (1) ; } ; /* Read float_data and check that it is normalised (ie default). */ if ((k = sf_read_float (file, float_data, BUFFER_LEN)) != BUFFER_LEN) { printf ("\n\nLine %d: sf_read_float failed with short read (%d ->%d)\n", __LINE__, BUFFER_LEN, k) ; exit (1) ; } ; for (k = 0 ; k < BUFFER_LEN ; k++) if (float_data [k] >= 1.0) { printf ("\n\nLine %d: float_data [%d] == %f which is greater than 1.0\n", __LINE__, k, float_data [k]) ; exit (1) ; } ; /* Seek to start of file, turn normalisation off, read float_data and check again. */ sf_seek (file, 0, SEEK_SET) ; sf_command (file, SFC_SET_NORM_FLOAT, NULL, SF_FALSE) ; if ((k = sf_read_float (file, float_data, BUFFER_LEN)) != BUFFER_LEN) { printf ("\n\nLine %d: sf_read_float failed with short read (%d ->%d)\n", __LINE__, BUFFER_LEN, k) ; exit (1) ; } ; for (k = 0 ; k < BUFFER_LEN ; k++) if (float_data [k] < 1.0) { printf ("\n\nLine %d: float_data [%d] == %f which is less than 1.0\n", __LINE__, k, float_data [k]) ; exit (1) ; } ; /* Seek to start of file, turn normalisation on, read float_data and do final check. */ sf_seek (file, 0, SEEK_SET) ; sf_command (file, SFC_SET_NORM_FLOAT, NULL, SF_TRUE) ; if ((k = sf_read_float (file, float_data, BUFFER_LEN)) != BUFFER_LEN) { printf ("\n\nLine %d: sf_read_float failed with short read (%d ->%d)\n", __LINE__, BUFFER_LEN, k) ; exit (1) ; } ; for (k = 0 ; k < BUFFER_LEN ; k++) if (float_data [k] > 1.0) { printf ("\n\nLine %d: float_data [%d] == %f which is greater than 1.0\n", __LINE__, k, float_data [k]) ; exit (1) ; } ; sf_close (file) ; unlink (filename) ; printf ("ok\n") ; } /* float_norm_test */
EXIT_STATUS bb_encode( const char* _number, const char* _outfname ) { if ( !_number || !_outfname ) { fprintf( stderr, "NULL number(%c) || outfname(%c)\n" , ( _number ? 'f' : 'T' ) , ( _outfname ? 'f' : 'T' ) ); return ES_BADARG; } #ifdef _DEBUG /* ============================================================ */ printf( "'%s' -> '%s'\n" , _number , _outfname ); #endif /* =================================================================== */ /*check for number validity*/ int i = 0; for ( i = 0; i < strlen( _number ); i++ ) { if ( !index( DTMF_NUMBERS, _number[i] ) ) { fprintf( stderr, "incorrect character '%c'\n" "allowed characters are '%s'\n" , _number[i] , DTMF_NUMBERS ); return ES_BADARG; } } static const char* outext = ".wav"; char* outfname = (char*)calloc( strlen( _outfname ) + strlen( outext ) + 1 , sizeof(char) ); if ( !outfname ) { fprintf( stderr, "unable to allocate memory for extfilename\n" ); return ES_BAD; } strncpy( outfname , _outfname , strlen(_outfname) ); /*check for file extension*/ if ( !strstr( _outfname + strlen( _outfname ) - strlen( outext ), outext ) ) { strncpy( outfname + strlen( outfname ) , outext , strlen( outext ) ); } SF_INFO opt = { 0 }; opt.samplerate = DTMF_SAMPLE_RATE; opt.channels = 1; opt.format = SF_FORMAT_WAV | SF_FORMAT_FLOAT ; SNDFILE* ofd = sf_open( outfname , SFM_WRITE , &opt ); if ( !ofd ) { fprintf( stderr, "unable to open output file: %s\n" , sf_strerror( ofd ) ); return ES_BAD; } printf( "encoding '%s' to '%s'\n" , _number , outfname ); EXIT_STATUS es = ES_OK; /*run encoding*/ for ( i = 0; i < strlen( _number ); i++ ) { char c = _number[ i ]; #ifdef _DEBUG /* ============================================================ */ printf( "processing '%c' key\n" , c ); #endif /* =================================================================== */ DTMF_KEYPAD key = dtmf_c2kp( c ); if ( !dtmf_is_keypad_value( key ) ) { fprintf( stderr, "'%c'(position %d) -> %d - in not keypad value\n" , c , i , key ); es = ES_BAD; break; } if ( !DTMF_KEY_SIGNALS[ key ].filled ) { #ifdef _DEBUG /* ============================================================ */ printf( "generating '%c' key signal data\n" , c ); #endif /* =================================================================== */ if ( bbe_fill_key_signal( key ) != ES_OK ) { fprintf( stderr, "unable to fill signal data for key '%c'\n" , c ); es = ES_BAD; break; } } #ifdef _DEBUG /* ============================================================ */ else { printf( "'%c' signal already cached\n" , c ); } #endif /* =================================================================== */ if ( !DTMF_KEY_SIGNALS[ DTMF_KP_PAUSE ].filled ) { #ifdef _DEBUG /* ============================================================ */ printf( "generating pause signal data\n" ); #endif /* =================================================================== */ if ( bbe_fill_key_signal( DTMF_KP_PAUSE ) != ES_OK ) { fprintf( stderr, "unable to fill signal data for pause\n" ); es = ES_BAD; break; } } #ifdef _DEBUG /* ============================================================ */ else { printf( "pause signal already cached\n" ); } #endif /* =================================================================== */ sf_write_float( ofd , (float*)(DTMF_KEY_SIGNALS[ DTMF_KP_PAUSE ].data) , DTMF_KEY_SIGNALS[ DTMF_KP_PAUSE ].datasz ); sf_write_float( ofd , (float*)(DTMF_KEY_SIGNALS[ key ].data) , DTMF_KEY_SIGNALS[ key ].datasz ); } bbe_free_key_signals(); free( outfname ); sf_close( ofd ); printf( "encoding %s\n" , ( es == ES_OK ? "done" : "failed" ) ); return es; }
void ofxGSTT::audioIn(float * buffer,int bufferSize, int nChannels, int deviceId){ int deviceIdx=0; for(int i=0;i<deviceIds.size();++i){ if(deviceIds[i]==deviceId){ deviceIdx=i; break; } } if(bRecordingBlocked[deviceIdx]){//TODO ARRAY return; } float curVol = 0.0; // samples are "interleaved" int numCounted = 0; //lets go through each sample and calculate the root mean square which is a rough way to calculate volume for(int i = 0; i < bufferSize; i++){ left[i] = buffer[i * 2]; right[i] = buffer[i * 2 + 1]; curVol += left[i] * left[i]; curVol += right[i] * right[i]; numCounted += 2; }//TODO mehrfachverwendung von left & right - problem //this is how we get the mean of rms :) curVol /= (float) numCounted; // this is how we get the root of rms :) curVol = sqrt(curVol); smoothedVolume[deviceIdx] *= 0.9; //TODO settings for this ratio needed smoothedVolume[deviceIdx] += 0.1 * curVol; //lets scale the vol up to a 0-1 range //float scaledVol = ofMap(smoothedVol, 0.0, 0.17, 0.0, 1.0, true);//TODO set by settings! float scaledCurVolume = ofMap(curVol, 0.0, 0.17, 0.0, 1.0, true); bool bActiveVolume = scaledCurVolume > volumeThreshold; //TODO revisit: should be in an extra update function?! if(bActiveVolume){ timer[deviceIdx]->reset(); timer[deviceIdx]->startTimer(); bRecording[deviceIdx] = true; } if(bRecording[deviceIdx]){ if(timer[deviceIdx]->isTimerFinished()){ bRecording[deviceIdx] = false; finishRecording(deviceIdx); prepareRecording(deviceIdx); }else{ sf_write_float(outfiles[deviceIdx], buffer, bufferSize * 2); } } // // if(deviceId>10){ // delete[] buffer; // } }
static int audio_callback( const void *inputBuffer, void *outputBuffer, unsigned long framesPerBuffer, const PaStreamCallbackTimeInfo *timeInfo, PaStreamCallbackFlags statusFlags, void *userData ) { int i; float *out = (float*)outputBuffer; float b, d, f, mod; int beat; float v; for( i = 0; i < framesPerBuffer; i++ ) { d = 0; beat = global_frame % ( SAMPLE_RATE / ( DEFAULT_BPM / 60 ) / 4 ); if( beat == 0 ) { if( beat_count % 4 == 0 ) bass_lfofreq = ((float)DEFAULT_BPM/60.0f) * flt_freq[ rand()%4 ]; if( rand()%RANDOM_NOTE_CHANGE_CHANCE == 0 ) { bass_freq = midi_to_hz( BASE_NOTE + minor_scale[ rand()%7 ] + ((rand()%RANDOM_OCTAVE_JUMP_CHANCE==0)?12:0) ); } if( ( beat_count % 4 == 0 ) && ( rand()%RANDOM_GLITCH_CHANCE == 0 ) ) { bass_fmindex = (float)( rand()%999 + 1 ); } if( ( beat_count % 4 == 0 ) && ( rand()%RANDOM_GLITCH_RETURN_CHANCE == 0 ) ) { bass_fmindex = 0.0f; } if( rand()%RANDOM_MODULATION == 0 ) { bass_fmmod = (float)( rand()%3 + 1 ); } if( beat_count % 16 == 0 ) bd_time = 0; if( beat_count % 16 == 8 ) { if( rand()%RANDOM_SNARE_SILENCE_CHANCE == 0 ) bass_vol = 0.0f; sd_time = 0; } if( ( beat_count % 16 == 10 ) && ( rand()%RANDOM_SNARE_CHANCE == 0 ) ) sd_time = 0; if( beat_count % 16 == 12 ) bass_vol = 1.0f; if( beat_count % 16 == 6 ) bd_time = 0; if( beat_count % 2 == 0 ) hh_time = 0; beat_count++; } if( bd_time >= 0 ) { d = bd[bd_time++]; if( bd_time > SAMPLE_RATE ) bd_time = -1; } if( sd_time >= 0 ) { d = d * 0.8f + sd[sd_time++]; if( sd_time > SAMPLE_RATE ) sd_time = -1; } if( hh_time >= 0 ) { d = d * 0.8f + hh[hh_time++] * 0.05f; if( hh_time > SAMPLE_RATE ) hh_time = -1; } bass_lfoval = sin( 2.0 * M_PI * bass_lfofreq * (float)global_frame / (float)SAMPLE_RATE ); bass_lfoval = bass_lfoval/100.0f + 0.99f; mod = sin( 2.0 * M_PI * bass_fmmod * bass_freq * (float)global_frame / (float)SAMPLE_RATE ); b = sgn( sin( 2.0 * M_PI * ( bass_freq * (float)global_frame / (float)SAMPLE_RATE ) + mod * bass_fmindex ) ); bass_z = bass_lfoval * bass_z + ( 1.0f - bass_lfoval ) * b; v = 0.3f; out[i] = bass_vol * bass_z * v + d * ( 1.0f-v ); if( out[i] > 1.0f ) out[i] = 1.0f; if( out[i] < -1.0f ) out[i] = -1.0f; global_frame++; } sf_write_float( wave_output, out, framesPerBuffer ); if (to_stdout) { for (i = 0; i < framesPerBuffer; i++) { double f = (double)out[i]; convert_buf[i] = (int32_t)(f * 0x7fffffffL); } write(STDOUT_FILENO, convert_buf, framesPerBuffer * 4); } if (mute) memset(out, 0, sizeof(float) * framesPerBuffer); return paContinue; }
int main(int argc, char *argv[]) { long i = 0; long readcount = 0; PaStreamParameters inputParameters; PaStream *stream = NULL; long sizeonesec = (PLAY_FRAMES_PER_BUFFER * 2) * sizeof(float); /* Alloc size for one block */ float *sampleBlock = (float *)malloc(sizeonesec); PaError retval = 0; struct sigaction sa; printf("Record to file: '%s'\n", argv[1]); /* We use two channels Samplerate is 44100 Wave 16 bit output format */ sfinfo.channels = 2; sfinfo.samplerate = 44100; sfinfo.format = SF_FORMAT_WAV | SF_FORMAT_PCM_16; /* Open file. Because this is just a example we asume What you are doing and give file first argument */ if (! (outfile = sf_open(argv[1], SFM_WRITE, &sfinfo))) { printf ("Not able to open output file %s.\n", argv[1]) ; sf_perror (NULL) ; return 1 ; } sa.sa_flags = SA_SIGINFO; sigemptyset(&sa.sa_mask); sa.sa_sigaction = handler; if (sigaction(SIGINT, &sa, NULL) == -1) { printf("Can't set SIGINT handler!\n"); sf_close(outfile); return -1; } if (sigaction(SIGHUP, &sa, NULL) == -1) { printf("Can't set SIGHUP handler!\n"); sf_close(outfile); return -1; } /* -- initialize PortAudio -- */ retval = Pa_Initialize(); if(retval != paNoError) { goto exit; } inputParameters.device = Pa_GetDefaultInputDevice(); /* default output device */ if (inputParameters.device == paNoDevice) { fprintf(stderr, "Error: No default output device.\n"); goto exit; } /* -- setup stream -- */ inputParameters.channelCount = 2; /* stereo output */ inputParameters.sampleFormat = paFloat32; /* 32 bit floating point output */ inputParameters.suggestedLatency = Pa_GetDeviceInfo(inputParameters.device)->defaultLowOutputLatency; inputParameters.hostApiSpecificStreamInfo = NULL; retval = Pa_OpenStream( &stream, &inputParameters, NULL, /* no output */ 44100, PLAY_FRAMES_PER_BUFFER, paClipOff, /* we won't output out of range samples so don't bother clipping them */ NULL, outfile); if(retval != paNoError) { printf("Can't open device\n"); goto exit; } /* -- start stream -- */ retval = Pa_StartStream(stream); if(retval != paNoError) { goto exit; } printf("Wire on. Will run one minute.\n"); fflush(stdout); /* -- Here's the loop where we pass data from input to output -- */ for(i = 0; i < ((10 * sizeonesec) / (44100 * 2)); ++i) { retval = Pa_ReadStream(stream, (void *)sampleBlock, sizeonesec / 8); if(retval != paNoError) { printf("** Can't read from input!\n"); goto exit; } readcount = sf_write_float(outfile, sampleBlock, sizeonesec / 4); if(readcount <= 0) { printf("** Can't write to file!\n"); goto exit; } } exit: sf_close(outfile); retval = Pa_StopStream(stream); retval = Pa_CloseStream(stream); Pa_Terminate(); return 0; }
int main( int argc, char** argv ) { if ( argc < 3 ) { printf( "specify input and output files\n" ); return 1; } const char* infname = argv[1]; const char* ofname = argv[2]; printf( "'%s' -> '%s'\n" , infname , ofname ); FILE* ifd = fopen( infname, "r" ); if ( !ifd ) { printf( "unable to open in file\n" ); return 1; } SF_INFO opt; memset( &opt, 0, sizeof(opt) ); opt.samplerate = 8000; opt.channels = 1; opt.format = SF_FORMAT_WAV | SF_FORMAT_FLOAT ; SNDFILE* ofd = sf_open( ofname , SFM_WRITE , &opt ); if ( !ofd ) { printf( "unable to open out file: '%s'\n" , sf_strerror( ofd ) ); fclose( ifd ); return 1; } char line[BUFSZ]; memset( line, 0, sizeof(line) ); char c = 0x00; int p = 0x00; do { if ( '\n' == c ) { line[p] = 0x00; if ( strlen( line ) ) { float t = 0x00; float v = 0x00; int r = sscanf( line , "%f\t%f" , &t , &v ); if ( r != 2 ) { printf( "unable to parse line\n" ); } /*write file*/ sf_write_float( ofd , &v , 1 ); } p = 0x00; } c = fgetc( ifd ); line[ p++ ] = c; } while ( c != EOF ); fclose( ifd ); sf_close( ofd ); return 0; }
size_t wav_write(SNDFILE *wav, const quiet_sample_t *samples, size_t sample_len) { return sf_write_float(wav, samples, sample_len); }
int main (void) { /* This is a buffer of double precision floating point values ** which will hold our data while we process it. */ static float data [BUFFER_LEN] ; /* A SNDFILE is very much like a FILE in the Standard C library. The ** sf_open function return an SNDFILE* pointer when they sucessfully ** open the specified file. */ SNDFILE *infile, *outfile ; /* A pointer to an SF_INFO stutct is passed to sf_open. ** On read, the library fills this struct with information about the file. ** On write, the struct must be filled in before calling sf_open. */ SF_INFO sfinfo ; int readcount ; const char *infilename = "input.wav" ; const char *outfilename = "output.wav" ; /* Here's where we open the input file. We pass sf_open the file name and ** a pointer to an SF_INFO struct. ** On successful open, sf_open returns a SNDFILE* pointer which is used ** for all subsequent operations on that file. ** If an error occurs during sf_open, the function returns a NULL pointer. ** ** If you are trying to open a raw headerless file you will need to set the ** format and channels fields of sfinfo before calling sf_open(). For ** instance to open a raw 16 bit stereo PCM file you would need the following ** two lines: ** ** sfinfo.format = SF_FORMAT_RAW | SF_FORMAT_PCM_16 ; ** sfinfo.channels = 2 ; */ if (! (infile = sf_open (infilename, SFM_READ, &sfinfo))) { /* Open failed so print an error message. */ printf ("Not able to open input file %s.\n", infilename) ; /* Print the error message from libsndfile. */ puts (sf_strerror (NULL)) ; return 1 ; } ; if (sfinfo.channels > MAX_CHANNELS) { printf ("Not able to process more than %d channels\n", MAX_CHANNELS) ; return 1 ; } ; /* Open the output file. */ if (! (outfile = sf_open (outfilename, SFM_WRITE, &sfinfo))) { printf ("Not able to open output file %s.\n", outfilename) ; puts (sf_strerror (NULL)) ; return 1 ; } ; /* While there are.frames in the input file, read them, process ** them and write them to the output file. */ while ((readcount = sf_read_float (infile, data, BUFFER_LEN))) { process_data (data, readcount, sfinfo.channels) ; sf_write_float (outfile, data, readcount) ; } ; /* Close input and output files. */ sf_close (infile) ; sf_close (outfile) ; return 0 ; } /* main */
int OlaRandom::WriteSoundFile( char filename[], float * data, int datasize ) { if( m_winsize != datasize ) { hanna( m_window, datasize ); m_winsize = datasize; } apply_window( data, m_window, datasize ); /*int hopsize = segsize / 2; //m_last_buffer_size / 2; //m_last_buffer_size - datasize / 2; if( hopsize < 0 ) hopsize = 0; BirdBrain::ola( m_ola_buffer, data, hopsize, datasize ); m_last_buffer_size = datasize; // reset data and datasize for writing memcpy( data, m_ola_buffer, sizeof(float) * hopsize ); datasize = hopsize; */ if( !m_top ) m_hopsize = m_last_buffer_size / 2; //fprintf( stderr, "hop: %d\n", m_hopsize ); m_top = !m_top; memcpy( m_swap_buffer, m_ola_buffer, sizeof(float) * m_hopsize ); BirdBrain::ola( m_ola_buffer, data, m_hopsize, OLAR_BIG_BUFFER_SIZE, datasize ); m_last_buffer_size = datasize; memcpy( data, m_swap_buffer, sizeof(float) * m_hopsize ); datasize = m_hopsize; // data will always fit in one buffer because buffer size = max tree size (CUTOFF) if( this->write_to_buffer ) { while( m_data_count >= m_max_data_count ) { BB_log( BB_LOG_FINE, "Background: waiting for empty buffer" ); usleep( 2000 ); } // used to be if ... return 0; // set #samples for the write buffer if( m_buffer_samples[m_write_index] != 0 ) { BB_log( BB_LOG_WARNING, "Background: overwriting!" ); } m_buffer_samples[m_write_index] = datasize; // set the buffer to write float * next_buffer = m_big_buffer[m_write_index++]; m_write_index %= m_max_data_count; // copy the data memcpy( next_buffer, data, datasize * sizeof(float) ); // increment data count m_data_count++; /* fprintf( stderr, "+ " ); for( int i = 0; i < m_max_data_count; i++ ) fprintf( stderr, "%d ", m_buffer_samples[i] ); fprintf( stderr, "(%d)\n", datasize ); */ } // if it's also writing to buffer, it doesn't get here until after the write succeeds // so the same data should not be written more than once to the file int itemswritten = 0; if( this->write_to_file ) { if( !sfwrite ) { writeinfo = readinfo; sfwrite = sf_open( filename, SFM_RDWR, &writeinfo ); if( !sfwrite ) { std::cerr << "OlaRandom::WriteSoundFile : cannot open file '" << filename << "', quitting" << std::endl; //char x[256]; //std::cin.getline( x, 256 ); //exit(1); return 2; } } sf_seek( sfwrite, writeinfo.frames, SEEK_SET ); itemswritten = sf_write_float( sfwrite, data, datasize ); if( itemswritten <= 0 ) { std::cerr << "OlaRandom::WriteSoundFile : cannot write to file '" << filename << "'" << std::endl; std::cerr << "needed to write " << datasize << " samples" << std::endl; //char x[256]; //std::cin.getline( x, 256 ); //exit(3); return 2; } sf_close( sfwrite ); sfwrite = NULL; } // wrote something if( this->write_to_file ) return itemswritten; else return datasize; }
int write_audio_buffer_float(struct audio_out_t *out, float* buffer, int size) { sf_count_t amnt_written; amnt_written = sf_write_float(out->sf, buffer, (sf_count_t) size); return amnt_written == (sf_count_t) size; }
//-------------------------------------------------------------- void testApp::setup(){ ofBackground(255,255,255); // 2 output channels, // 0 input channels // 22050 samples per second // 256 samples per buffer // 4 num buffers (latency) // ofSetDataPathRoot("../bin/data/"); sampleRate = 44100; phase = 0; phaseAdder = 0.0f; phaseAdderTarget = 0.0f; volume = 0.1f; bNoise = false; lAudio = new float[256]; rAudio = new float[256]; ofSoundStreamSetup(2,0,this, sampleRate,256, 4); ofSetFrameRate(60); fvec_t * my_fvec_t; aubio_onset_t* my_aubio_result; aubio_onsetdetection_t * my_onset_detection; scrollWidth = 1600; int readcount = 0; // counts number of samples read from sound file //string inputFilename = "sound/GetIntoTheGroove.wav";// input file name placed in bin sfinfo.format = 0; moveOn = true; energyIndex = 0; frameIndex = 0; chromaIndex = 0; chromoGramm.initialise(FRAMESIZE,2048);//framesize 512 and hopsize 2048 loadSoundFiles(); readcount = 1; while(readcount != 0 && moveOn == true) { // read FRAMESIZE samples from 'infile' and save in 'data' readcount = sf_read_float(infile, frame, FRAMESIZE); //processing frame - downsampled to 11025Hz //8192 samples per chroma frame chromoGramm.processframe(frame); if (chromoGramm.chromaready) { if (chromaIndex < ENERGY_LENGTH/CHROMA_CONVERSION_FACTOR){// && energyIndex < ENERGY_LENGTH){//dont exceed vector length for (int i = 0;i<12;i++){ chromoGramVector[chromaIndex][i] = chromoGramm.rawChroma[i] / chromoGramm.maximumChromaValue; } //this would do chord detection chord.C_Detect(chromoGramm.chroma,chromoGramm.chroma_low); rootChord[chromaIndex] = chord.root; chromaIndex++; } } // printf ("Root %i", chord.root); //get energy of the current frame and wait getEnergyOfFrame(); // write 'readcount' samples from 'frame' to 'outfile' sf_write_float(outfile, frame, readcount) ; } totalNumberOfFrames = frameIndex; printf("Total frames %i energy index %i and Chroma index %i", frameIndex, energyIndex, chromaIndex); /* ////// NEw soundfile test // Open the sound file SF_INFO FileInfos; string Filename = "../../../GetIntoTheGroove.wav"; SNDFILE* File = sf_open(Filename.c_str(), SFM_READ, &FileInfos); if (File) { sf_close(File); printf("SF CLOSE : closed file okay"); } else { switch(sf_error(File)) { case SF_ERR_UNRECOGNISED_FORMAT: ofLog(OF_LOG_ERROR,"ofxSoundPlayer loading file - unrecognised format"); break; case SF_ERR_SYSTEM: ofLog(OF_LOG_ERROR,"ofxSoundPlayer loading file - system error"); break; case SF_ERR_MALFORMED_FILE: ofLog(OF_LOG_ERROR,"ofxSoundPlayer loading file - malformed file"); break; case SF_ERR_UNSUPPORTED_ENCODING: ofLog(OF_LOG_ERROR,"ofxSoundPlayer loading file - unsupported encoding"); break; default: ofLog(OF_LOG_ERROR,"ofxSoundPlayer loading file - unknown error"); break; }; } */ //end new soundfile ftest }
int main(int argc, char **argv) { SNDFILE *soundfile = NULL; SF_INFO info; SNDFILE *soundfile_out = NULL; SF_INFO info_out; float integrator=0.0; float error_signal=0.0; float out=0.0; int i,j,k; int count; int error; int ttyfd=-1; struct termios oldtio,newtio; unsigned char outbyte; SRC_STATE *samplerate; SRC_DATA resample_data; SRC_STATE *samplerate_out; SRC_DATA resample_data_out; info.format=0; int quiet = 0; char device[128]; char outfile[1024]; char infile[1024]; char output[1024]; int rate = 48000; strcpy(device, "/dev/ttyS0"); strcpy(output, device); int opt; while ((opt = getopt(argc, argv, "qd:r:w:")) != -1) { switch(opt) { case 'd': strcpy(device, optarg); strcpy(output, device); break; case 'r': rate = atoi(optarg); break; case 'w': strcpy(outfile, optarg); strcpy(output, outfile); break; case 'q': quiet = 1; break; } } if (optind >= argc) { fprintf(stderr, "Usage:\t%s [-q] [-r sample_rate] [-d device | -w out.wav] in.wav\n", argv[0]); return 1; } else strcpy(infile, argv[optind]); if (!quiet) fprintf(stderr,"Playing:\t%s\nOutput:\t\t%s\nSample rate:\t%d\n", infile, output, rate); soundfile=sf_open(infile,SFM_READ,&info); info_out.samplerate=rate; info_out.channels=1; info_out.format=SF_FORMAT_PCM_16|SF_FORMAT_WAV; if (strlen(outfile) > 1) { soundfile_out=sf_open(outfile,SFM_WRITE,&info_out); if ((soundfile==NULL) || (soundfile_out==NULL)) { fprintf(stderr,"Couldn't open that file. Sorry.\n"); return 1; } } else { // we're not writing an output file, try serial I/O // blocking I/O blocks forever on open(), dunno why. ttyfd = open(device, O_RDWR|O_NOCTTY|O_NONBLOCK); if (ttyfd <0) {perror(device); exit(-1); } tcgetattr(ttyfd,&oldtio); /* save current serial port settings */ bzero(&newtio, sizeof(newtio)); /* clear struct for new port settings */ cfmakeraw(&newtio); if (0!=cfsetospeed(&newtio,SERIAL_BAUDRATE)) { perror(device); exit(-1); } if (0!=tcflush(ttyfd, TCIFLUSH)) { perror(device); exit(-1); } if (0!=tcsetattr(ttyfd,TCSANOW,&newtio)) { perror(device); exit(-1); } } samplerate=src_new(SRC_LINEAR,1,&error); if (error) { fprintf(stderr,"Samplerate error. Sorry.\n"); return 1; } samplerate_out=src_new(SRC_SINC_FASTEST,1,&error); if (error) { fprintf(stderr,"Samplerate error. Sorry.\n"); return 1; } resample_data.data_in=(float *)malloc((int)(SOUND_BUFFER_LEN*info.samplerate*info.channels)*sizeof(float)); resample_data.data_out=(float *)malloc(2*(int)(SOUND_BUFFER_LEN*BAUDRATE)*sizeof(float)); resample_data.src_ratio=((float)BAUDRATE)/(float)info.samplerate; resample_data.end_of_input=0; resample_data.output_frames=(int)2*BAUDRATE*SOUND_BUFFER_LEN; resample_data_out.data_in=(float *)malloc(2*BAUDRATE*sizeof(float)); resample_data_out.data_out=(float *)malloc(2*(int)(SOUND_BUFFER_LEN*rate)*sizeof(float)); resample_data_out.src_ratio=((float)rate)/((float)BAUDRATE); resample_data_out.end_of_input=0; resample_data_out.output_frames=(int)(2*rate*SOUND_BUFFER_LEN); k=0; while ((count=sf_readf_float(soundfile,resample_data.data_in,(int)(SOUND_BUFFER_LEN*info.samplerate)))) { // make mono for (j=0; j<count; j++) { resample_data.data_in[j]=resample_data.data_in[j*info.channels]; for (i=1; i<info.channels; i++) { resample_data.data_in[j]+=resample_data.data_in[j*info.channels+i]; } resample_data.data_in[j]/=(float)info.channels; } resample_data.input_frames=count; // following has a bug... if (count<(int)(SOUND_BUFFER_LEN*info.samplerate)) { resample_data.end_of_input=1; resample_data_out.end_of_input=1; } src_process(samplerate,&resample_data); // Now we have our input signal converted to the serial baudrate. All that's left is sigma-delta modulate // and write to the serial port outbyte=0; for (j=0; j<resample_data.output_frames_gen; j++) { error_signal=resample_data.data_out[j]-out; integrator+=error_signal; switch (k%10) { case 0: outbyte=0; out=-1.0; //start bit break; case 9: out=1.0; //stop bit if (ttyfd>=0) { while ( 1!=write(ttyfd,&outbyte,1)) { /* What's a spinloop among friends? */ ; } } break; default: out=(integrator>0) ? 1.0 : -1.0; if (out>0.0) outbyte |= 1<<((k%10)-1); } resample_data_out.data_in[j]=out; k++; } if (soundfile_out) { resample_data_out.input_frames=resample_data.output_frames_gen; src_process(samplerate_out,&resample_data_out); i=sf_write_float(soundfile_out, resample_data_out.data_out, resample_data_out.output_frames_gen); } } sf_close(soundfile); if (soundfile_out) sf_close(soundfile_out); // restore serial port settings if (ttyfd>=0) { tcsetattr(ttyfd,TCSANOW,&oldtio); } return 0; }
bool TransientExtractor::remove_transients( const char *outfilename, std::vector< uint > rmindexs ) { TransLoc tl; int tranLen, gapLen, postgapLen, overlap, pad = allowableGap / 4, tstart, mingapLen; //float prenoise, postnoise, noise; //int count, noiselen = allowableGap; Treesynth ts; Tree * ts_tree = NULL; // gets deleted from inside treesynth int levels; SAMPLE * syn; SAMPLE * buffer = NULL; // Read original file AudioSrcFile * orig = new AudioSrcFile; orig->open( filename.c_str(), 0, 0, FALSE ); uint size = orig->info().frames; SAMPLE * working = new SAMPLE[size]; orig->mtick( working, size ); // Open output file SF_INFO sf_info_write = orig->info(); sf_info_write.channels = 1; SNDFILE * out = sf_open( outfilename, SFM_WRITE, &sf_info_write ); // "bitmap" of transients bool * bmp = new bool[size]; for( int b = 0; b < size; b++ ) bmp[b] = false; for( int t = 0; t < transients.size(); t++ ) { tl = transients[t]; for( int b = estart + tl.start; b < estart + tl.end; b++ ) bmp[b] = true; } for( int r = 0; r < rmindexs.size(); r++ ) { tl = transients[rmindexs[r]]; tstart = tl.start - pad; if( tstart < 0 ) tstart = 0; tranLen = tl.end - tstart; mingapLen = tranLen/4; // inefficiently find size of nearest preceding transient-free zone int e = estart + tstart; gapLen = 0; while( gapLen < 2 * tranLen && e > 0 ) { e--; if( !bmp[e] ) gapLen++; else if( gapLen <= mingapLen ) gapLen = 0; else break; } // and nearest _next_ free zone int f = estart + tl.end; postgapLen = 0; while( postgapLen < 2 * tranLen && f < size-1 ) { f++; if( !bmp[f] ) postgapLen++; else if( postgapLen <= mingapLen ) postgapLen = 0; else break; } // find final gap length bool pre = false, post = false; if( postgapLen <= mingapLen ) { pre = true; } else if( gapLen <= mingapLen ) { post = true; gapLen = postgapLen; } else gapLen = postgapLen < gapLen ? postgapLen : gapLen; fprintf( stderr, "%s %s %i %i %i\n", pre ? "true" : "false", post ? "true" : "false", gapLen, 2*tranLen, mingapLen ); if( gapLen <= 0 ) continue; // add non-trans zones SAFE_DELETE_ARRAY( buffer ); buffer = new SAMPLE[gapLen]; for( int g = 0; g < gapLen; g++ ) { if( pre ) buffer[g] = working[e + g]; else if( post ) buffer[g] = working[f - postgapLen + g]; else buffer[g] = (working[e + g] + working[f - postgapLen + g]) * 0.7; } levels = lg( gapLen ); gapLen = ::pow(2, levels); overlap = gapLen / 2; // zero out transient memset( working + estart + tstart, 0, tranLen * sizeof( SAMPLE ) ); // treesynth SAFE_DELETE( ts_tree ); ts_tree = new Tree; ts_tree->initialize( levels ); //memcpy( ts_tree->values(), working + e, gapLen * sizeof( SAMPLE ) ); memcpy( ts_tree->values(), buffer, gapLen * sizeof( SAMPLE ) ); ts.tree = ts_tree; ts.initialize(); ts.percentage = 0.8; ts.randflip = true; ts.stoplevel = 10; // if that's too big, it will stop at the last level automatically bool done = false; int index = estart + tstart - overlap; if( index < 0 ) index = 0; if( !ts.setup() ) return false; while( !done ) { fprintf( stderr, "a tree " ); ts.synth(); syn = ts.outputSignal(); // overlap add synthesized signal into working buffer for( int i = 0; i < gapLen; i++ ) { if( index + i < size ) { if( index + i < estart + tstart || index + i >= estart + tl.end ) working[index + i] *= 0.5; working[index + i] += 0.5 * syn[i]; //working[index + i] += syn[i]; //working[index + i] = 0.5 * working[index + i] + 0.5 * syn[i]; } else break; } index += (gapLen - overlap); if( index >= estart + tl.end ) done = true; } // noise floor? /*prenoise = postnoise = noise = 0; count = 0; int n; for( n = estart + tstart <= noiselen ? 0 : estart + tstart - noiselen; n < estart + tstart; n++, count++ ) { prenoise += fabs(working[n]); } prenoise /= (count > 0 ? count : 1); for( n = estart + tl.end, count = 0; n < size && n < estart + tl.end + noiselen; n++, count++ ) { postnoise += fabs(working[n]); } postnoise /= (count > 0 ? count : 1); for( n = estart + tstart, count = 0; n < estart + tl.end; n++, count++ ) { noise += fabs(working[n]); } noise /= (count > 0 ? count : 1); float slope = (postnoise - prenoise)/tranLen; if( noise != 0 ) slope /= noise; for( n = tstart; n < tl.end; n++ ) { working[estart + n] *= ( slope * n + prenoise ); }*/ // sigh of relief fprintf( stderr, "\n\n" ); } // Write out working sf_count_t write = sf_write_float( out, working, size ); // Close stuff sf_close( out ); SAFE_DELETE_ARRAY( working ); SAFE_DELETE_ARRAY( buffer ); return true; }
/* main function that makes the dubstep sound */ static int audio_callback( const void *inputBuffer, void *outputBuffer, unsigned long framesPerBuffer, const PaStreamCallbackTimeInfo *timeInfo, PaStreamCallbackFlags statusFlags, void *userData ) { int i; float *out = (float*)outputBuffer; float b, d, f, mod; int beat; float v; for( i = 0; i < framesPerBuffer; i++ ) { d = 0; beat = global_frame % ( SAMPLE_RATE / ( DEFAULT_BPM / 60 ) / 4 ); /* if the stream has hit a beat */ if( beat == 0 ) { /* 4 beats is half a measure; alter the filter's LFO */ if( beat_count % 4 == 0 ) bass_lfofreq = ((float)DEFAULT_BPM/60.0f) * flt_freq[ rand()%4 ]; /* change the note by choosing another from the provided scale */ if( rand()%RANDOM_NOTE_CHANGE_CHANCE == 0 ) { bass_freq = midi_to_hz( BASE_NOTE + minor_scale[ rand()%7 ] + ((rand()%RANDOM_OCTAVE_JUMP_CHANCE==0)?12:0) ); } /* alter the FM index (modulator amplitude), to add overtones to the bassline, thus creating the 'glitched' sound */ if( ( beat_count % 4 == 0 ) && ( rand()%RANDOM_GLITCH_CHANCE == 0 ) ) { bass_fmindex = (float)( rand()%999 + 1 ); } /* reset the FM index to return to the normal square bass sound */ if( ( beat_count % 4 == 0 ) && ( rand()%RANDOM_GLITCH_RETURN_CHANCE == 0 ) ) { bass_fmindex = 0.0f; } /* alter the FM mod (modulator frequency multiplier) */ if( rand()%RANDOM_MODULATION == 0 ) { bass_fmmod = (float)( rand()%3 + 1 ); } /* a bassdrum hits every two measures */ if( beat_count % 16 == 0 ) bd_time = 0; /* sometimes, the snare won't trigger */ if( beat_count % 16 == 8 ) { if( rand()%RANDOM_SNARE_SILENCE_CHANCE == 0 ) bass_vol = 0.0f; sd_time = 0; } /* trigger a snare drum on the 10th beat of two measures combined */ if( ( beat_count % 16 == 10 ) && ( rand()%RANDOM_SNARE_CHANCE == 0 ) ) sd_time = 0; /* reset the volume of the bassline, if it has been previously diminished, to create the impression of a compressor */ if( beat_count % 16 == 12 ) bass_vol = 1.0f; /* trigger a bass drum */ if( beat_count % 16 == 6 ) bd_time = 0; /* trigger a hihat */ if( beat_count % 2 == 0 ) hh_time = 0; beat_count++; } /* advance sample counters and mix the drum channel */ if( bd_time >= 0 ) { d = bd[bd_time++]; if( bd_time > SAMPLE_RATE ) bd_time = -1; } if( sd_time >= 0 ) { d = d * 0.8f + sd[sd_time++]; if( sd_time > SAMPLE_RATE ) sd_time = -1; } if( hh_time >= 0 ) { d = d * 0.8f + hh[hh_time++] * 0.05f; if( hh_time > SAMPLE_RATE ) hh_time = -1; } /* compute the LFO value */ bass_lfoval = sin( 2.0 * M_PI * bass_lfofreq * (float)global_frame / (float)SAMPLE_RATE ); /* the LFO value is in range 0.00 .. 0.01 */ bass_lfoval = bass_lfoval/100.0f + 0.99f; /* compute the modulator */ mod = sin( 2.0 * M_PI * bass_fmmod * bass_freq * (float)global_frame / (float)SAMPLE_RATE ); /* compute the bassline */ b = sgn( sin( 2.0 * M_PI * ( bass_freq * (float)global_frame / (float)SAMPLE_RATE ) + mod * bass_fmindex ) ); /* process the bassline through a lowpass filter */ bass_z = bass_lfoval * bass_z + ( 1.0f - bass_lfoval ) * b; v = 0.3f; /* final mix of the two tracks */ out[i] = bass_vol * bass_z * v + d * ( 1.0f-v ); if( out[i] > 1.0f ) out[i] = 1.0f; if( out[i] < -1.0f ) out[i] = -1.0f; global_frame++; } sf_write_float( wave_output, out, framesPerBuffer ); return paContinue; }
void EngineRecord::process(const CSAMPLE* pBuffer, const int iBufferSize) { float recordingStatus = m_pRecReady->get(); if (recordingStatus == RECORD_OFF) { //qDebug("Setting record flag to: OFF"); if (fileOpen()) { Event::end("EngineRecord recording"); closeFile(); // Close file and free encoder. emit(isRecording(false)); } } else if (recordingStatus == RECORD_READY) { // If we are ready for recording, i.e, the output file has been selected, we // open a new file. updateFromPreferences(); // Update file location from preferences. if (openFile()) { Event::start("EngineRecord recording"); qDebug("Setting record flag to: ON"); m_pRecReady->set(RECORD_ON); emit(isRecording(true)); // will notify the RecordingManager // Since we just started recording, timeout and clear the metadata. m_iMetaDataLife = kMetaDataLifeTimeout; m_pCurrentTrack = TrackPointer(); // clean frames couting and get current sample rate. m_frames = 0; m_sampleRate = m_pSamplerate->get(); if (m_bCueIsEnabled) { openCueFile(); m_cueTrack = 0; } } else { // Maybe the encoder could not be initialized qDebug("Setting record flag to: OFF"); m_pRecReady->slotSet(RECORD_OFF); emit(isRecording(false)); } } else if (recordingStatus == RECORD_ON) { // If recording is enabled process audio to compressed or uncompressed data. if (m_encoding == ENCODING_WAVE || m_encoding == ENCODING_AIFF) { if (m_pSndfile != NULL) { sf_write_float(m_pSndfile, pBuffer, iBufferSize); emit(bytesRecorded(iBufferSize * 2)); } } else { if (m_pEncoder) { // Compress audio. Encoder will call method 'write()' below to // write a file stream m_pEncoder->encodeBuffer(pBuffer, iBufferSize); } } // update frames counting and recorded duration (seconds) m_frames += iBufferSize / 2; unsigned long lastDuration = m_recordedDuration; m_recordedDuration = m_frames / m_sampleRate; // gets recorded duration and emit signal that will be used // by RecordingManager to update the label besides start/stop button if (lastDuration != m_recordedDuration) { emit(durationRecorded(getRecordedDurationStr())); } if (m_bCueIsEnabled) { if (metaDataHasChanged()) { m_cueTrack++; writeCueLine(); m_cueFile.flush(); } } } }
/* Collect read stats */ printf (" Read %-5s from %s : ", "int", subtype) ; fflush (stdout) ; clock_time = 0 ; op_count = 0 ; start_clock = clock () ; while (clock_time < (CLOCKS_PER_SEC * TEST_DURATION)) { if (! (file = sf_open (filename, SFM_READ, &sfinfo))) { printf ("Error : not able to open file : %s\n", filename) ; perror ("") ; exit (1) ; } ; for (k = 0 ; k < BLOCK_COUNT ; k++) { if ((retval = sf_read_int (file, int_data, item_count)) != item_count) { printf ("Error : write returned %d (should have been %d)\n", retval, item_count) ; exit (1) ; } ; } ; sf_close (file) ; clock_time = clock () - start_clock ; op_count ++ ; } ; performance = (1.0 * item_count) * BLOCK_COUNT * op_count ; performance *= (1.0 * CLOCKS_PER_SEC) / clock_time ; printf ("%6.2f%% of raw read\n", 100.0 * performance / read_rate) ; unlink (filename) ; } /* calc_int_performance */ static void calc_float_performance (int format, double read_rate, double write_rate) { SNDFILE *file ; SF_INFO sfinfo ; clock_t start_clock, clock_time ; double performance ; int k, item_count, retval, op_count ; const char* subtype ; float *float_data ; char *filename ; filename = "benchmark.dat" ; subtype = get_subtype_str (format & SF_FORMAT_SUBMASK) ; float_data = data ; item_count = BUFFER_SIZE ; for (k = 0 ; k < item_count ; k++) float_data [k] = 1.0 * sin (2 * M_PI * k / 32000.0) ; /* Collect write stats */ printf (" Write %-5s to %s : ", "float", subtype) ; fflush (stdout) ; sfinfo.channels = 1 ; sfinfo.format = format ; sfinfo.frames = 1 ; sfinfo.samplerate = 32000 ; clock_time = 0 ; op_count = 0 ; start_clock = clock () ; while (clock_time < (CLOCKS_PER_SEC * TEST_DURATION)) { if (! (file = sf_open (filename, SFM_WRITE, &sfinfo))) { printf ("Error : not able to open file : %s\n", filename) ; perror ("") ; exit (1) ; } ; /* Turn off the addition of a PEAK chunk. */ sf_command (file, SFC_SET_ADD_PEAK_CHUNK, NULL, SF_FALSE) ; for (k = 0 ; k < BLOCK_COUNT ; k++) { if ((retval = sf_write_float (file, float_data, item_count)) != item_count) { printf ("Error : sf_write_short returned %d (should have been %d)\n", retval, item_count) ; exit (1) ; } ; } ; sf_close (file) ; clock_time = clock () - start_clock ; op_count ++ ; } ; performance = (1.0 * BUFFER_SIZE) * BLOCK_COUNT * op_count ; performance *= (1.0 * CLOCKS_PER_SEC) / clock_time ; printf ("%6.2f%% of raw write\n", 100.0 * performance / write_rate) ; /* Collect read stats */ printf (" Read %-5s from %s : ", "float", subtype) ; fflush (stdout) ; clock_time = 0 ; op_count = 0 ; start_clock = clock () ; while (clock_time < (CLOCKS_PER_SEC * TEST_DURATION)) { if (! (file = sf_open (filename, SFM_READ, &sfinfo))) { printf ("Error : not able to open file : %s\n", filename) ; perror ("") ; exit (1) ; } ; for (k = 0 ; k < BLOCK_COUNT ; k++) { if ((retval = sf_read_float (file, float_data, item_count)) != item_count) { printf ("Error : write returned %d (should have been %d)\n", retval, item_count) ; exit (1) ; } ; } ; sf_close (file) ; clock_time = clock () - start_clock ; op_count ++ ; } ; performance = (1.0 * item_count) * BLOCK_COUNT * op_count ; performance *= (1.0 * CLOCKS_PER_SEC) / clock_time ; printf ("%6.2f%% of raw read\n", 100.0 * performance / read_rate) ; unlink (filename) ; } /* calc_float_performance */