Skip to content

Instantly share code, notes, and snippets.

@Savantage
Created April 3, 2019 16:34
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Savantage/1675b81641b7e44134ac9797aad64b8d to your computer and use it in GitHub Desktop.
Save Savantage/1675b81641b7e44134ac9797aad64b8d to your computer and use it in GitHub Desktop.
Help with wav file...
#include <iostream> // for cout/cin
#include <fstream> // for files
#include <cstdint> // for fixed ints
#include <cmath> // for sin funct
using namespace std;
#define FORMAT_AUDIO 1
#define FORMAT_SIZE 16
struct wave_header{
// Header
char riff[4]; // "RIFF"
int32_t file_size; // Tamaño total del archivo a partir del byte 8
char wave[4]; // "WAVE"
// Format
char fmt[4]; // "fmt "
int32_t format_size; // Tamaño del formato
int16_t format_audio; // Formato de audio
int16_t num_channels; // Cantidad de canales
int32_t sample_rate; // Muestras por segundo
int32_t byte_rate; // bytes por segundo
int16_t block_align; // block align
int16_t bits_per_sample; // bits por muestra
// Data
char data[4]; // "data"
int32_t data_size; // Tamaño total de los datos
};
void write_header(ofstream &music_file ,int16_t bits, int32_t samples, int32_t duration){
wave_header wav_header{};
int16_t channels_quantity = 1;
int32_t total_data = duration * samples * channels_quantity * bits/8;
int32_t file_data = 4 + 8 + FORMAT_SIZE + 8 + total_data;
wav_header.riff[0] = 'R';
wav_header.riff[1] = 'I';
wav_header.riff[2] = 'F';
wav_header.riff[3] = 'F';
wav_header.file_size = file_data;
wav_header.wave[0] = 'W';
wav_header.wave[1] = 'A';
wav_header.wave[2] = 'V';
wav_header.wave[3] = 'E';
wav_header.fmt[0] = 'f';
wav_header.fmt[1] = 'm';
wav_header.fmt[2] = 't';
wav_header.fmt[3] = ' ';
wav_header.format_size = FORMAT_SIZE;
wav_header.format_audio = FORMAT_AUDIO;
wav_header.num_channels = channels_quantity;
wav_header.sample_rate = samples;
wav_header.byte_rate = samples * channels_quantity * bits/8;
wav_header.block_align = static_cast<int16_t>(channels_quantity * bits / 8);
wav_header.bits_per_sample = bits;
wav_header.data[0] = 'd';
wav_header.data[1] = 'a';
wav_header.data[2] = 't';
wav_header.data[3] = 'a';
wav_header.data_size = total_data;
music_file.write((char*)&wav_header, sizeof(wave_header));
}
int main(int argc, char const *argv[]) {
int16_t bits = 8;
int32_t samples = 44100;
int32_t duration = 10;
ofstream music_file("music.wav", ios::out | ios::binary);
int32_t frame_total = samples * duration;
auto* audio = new int16_t[frame_total];
double chor = 493.9;
for(int i = 0; i < frame_total; i++){
audio[i] = static_cast<int16_t>(255 * sin(chor + i));
}
write_header(music_file, bits, samples, duration);
music_file.write((char*)&audio,sizeof(audio));
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment