Skip to content

Instantly share code, notes, and snippets.

@shiyuugohirao
Last active May 13, 2018 18:15
Show Gist options
  • Save shiyuugohirao/1cfd1bb5ec02cd135d4552c15c85cca2 to your computer and use it in GitHub Desktop.
Save shiyuugohirao/1cfd1bb5ec02cd135d4552c15c85cca2 to your computer and use it in GitHub Desktop.
convert ofSoundBuffer to ofBuffer
//--------------------------------------------------------------
// referrered to ofxSoundObjects
//--------------------------------------------------------------
ofBuffer makeWavBuffer(const ofSoundBuffer &buff){
// write a wav header
short myFormat = 1; // for pcm
int mySubChunk1Size = 16;
int bitsPerSample = 16; // assume 16 bit pcm
int myByteRate = buff.getSampleRate() * buff.getNumChannels() * bitsPerSample/8;
short myBlockAlign = buff.getNumChannels() * bitsPerSample/8;
int myChunkSize = 36 + buff.size()*bitsPerSample/8;
int myDataSize = buff.size()*bitsPerSample/8;
int channels = buff.getNumChannels();
int samplerate = buff.getSampleRate();
ofBuffer wav;
wav.append("RIFF", 4);
wav.append((char*) &myChunkSize, 4);
wav.append("WAVE", 4);
wav.append("fmt ", 4);
wav.append((char*) &mySubChunk1Size, 4);
wav.append((char*) &myFormat, 2); // should be 1 for PCM
wav.append((char*) &channels, 2); // # channels (1 or 2)
wav.append((char*) &samplerate, 4); // 44100
wav.append((char*) &myByteRate, 4); //
wav.append((char*) &myBlockAlign, 2);
wav.append((char*) &bitsPerSample, 2); //16
wav.append("data", 4);
wav.append((char*) &myDataSize, 4);
// write the wav file per the wav file format, 4096 bytes of data at a time.
const int WRITE_BUFF_SIZE = 4096;
short writeBuff[WRITE_BUFF_SIZE];
int pos = 0;
while(pos<buff.size()) {
int len = MIN(WRITE_BUFF_SIZE, buff.size()-pos);
for(int i = 0; i < len; i++) {
writeBuff[i] = (int)(buff[pos]*32767.f);
pos++;
}
wav.append((char*)writeBuff, len*bitsPerSample/8);
}
return wav;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment