I'm just trying to write a library for read and write Wav files (just need it for audio processing), just as test, I read samples from a Wave File convert them to double (just standardize them to -1 ~ 1), and do nothing but transform them back to integer, according to the bit per sample (assume the Wav file have N bits per sample, I divided them through 2^(N-1)-1 and multiply with the same factor after to restore it)
But the problem is, I get a wav file with background noise (id say it seems like quantisization noise) and I don't know why, can you help me find it out?
the library is here: https://pastebin.com/mz5TWMPN
the header file is: https://pastebin.com/Lr2tbmnv
and a demo main function is like:
#include <stdio.h>
#include <math.h>
#include "wavreader.h"
#define FRAMESIZE 512
int main()
{
FILE *fh;
FILE *fhWrite;
struct WavHeader * header;
struct WavHeader * newHeader;
double frame[FRAMESIZE];
int iBytesWritten;
int i;
char test;
fh = fopen("D:/ArbeitsOrdner/advanced_pacev/AudioSample/spfg.wav", "rb+");
if (fh == NULL)
{
printf("Failed to open organ.wav\n");
return 1;
}
fhWrite = fopen("D:/ArbeitsOrdner/MyC/test_organ.wav", "wb+");
if (fhWrite == NULL)
{
printf("Failed to create test_organ.wav\n");
return 1;
}
header = readWaveHeader(fh);
printWaveHeader(header);
newHeader = createWaveHeader(header->iChannels, header->iSampleRate, header->iBitsPerSample);
WaveWriteHeader(fhWrite, newHeader);
while (WaveReadFrame(fh, header, FRAMESIZE, frame) != -1)
{
iBytesWritten = WaveWriteFrame(fhWrite, newHeader, FRAMESIZE, frame);
if (iBytesWritten < 0)
{
printf("Error occured while writing to new file\n");
return 1;
}
}
WaveWriteHeader(fhWrite, newHeader);
fclose(fhWrite);
fclose(fh);
return 0;
}
thx for viewing this post. I have found the problem myself, it is that, i used char instead of unsigned char for raw data (raw bytes). By converting them to int16 or int32, i haven't considered the sign bit. that means they are not exact the same value during convertion as it except to be.
the solution for this is:
either stay with signed char and use:
buffer[i] & 0xff
to get the correct raw data for convertion, or change the char types into unsigned char:
unsgiend char * buffer;
Related
I am trying to read the data from SPH0645LM4H-B https://www.knowles.com/docs/default-source/model-downloads/sph0645lm4h-b-datasheet-rev-c.pdf?sfvrsn=4
and convert it to .wav format, so that I can verify whether my sensor is working correctly.
So far, I have managed to interface the sensor and read data samples via i2s-dma transfer.
Also, I found that most mainstream computer soundfile formats consist of a header (containing the length, etc.) followed by 16-bit two's-complement PCM https://www.dsprelated.com/freebooks/mdft/Number_Systems_Digital_Audio.html
For converting the PCM data to wave format, I have referred converting PCM to wav file
Now, the sensor data format is I2S, 24-bit, 2’s compliment, MSB first. The data precision is 18 bits; unused bits are zeros.
I have converted the sensor data to 32-bit (MSB is the sign bit)
I have used the code from the following link (and the links mentioned in it) to create the .wav file:-
Append .pcm audio raw data into wav (in C)
//.wav file header data
struct wavfile
{
char id[4]; // should always contain "RIFF"
int totallength; // total file length minus 8
char wavefmt[8]; // should be "WAVEfmt "
int format; // 16 for PCM format
short pcm; // WAVE_FORMAT_IEEE_FLOAT (3).
short channels; // channels
int frequency; // sampling frequency, 16000 in this case
int bytes_per_second;
short bytes_by_capture;
short bits_per_sample;
char data[4]; // should always contain "data"
int bytes_in_data;
};
//Writing the header to output .wav file
void write_wav_header(char* name, int samples, int channels)
{
struct wavfile filler;
FILE *pFile;
strcpy(filler.id, "RIFF");
filler.totallength = (samples * channels) + sizeof(struct wavfile) - 8;
strcpy(filler.wavefmt, "WAVEfmt ");
filler.format = 16;
filler.pcm = 3; // WAVE_FORMAT_IEEE_FLOAT (3).
filler.channels = channels;
filler.frequency = 32000;
filler.bits_per_sample = 32;
filler.bytes_per_second = filler.channels * filler.frequency * filler.bits_per_sample/8;
filler.bytes_by_capture = filler.channels*filler.bits_per_sample/8;
filler.bytes_in_data = samples * filler.channels * filler.bits_per_sample/8;
strcpy(filler.data, "data");
pFile = fopen(name, "wb");
fwrite(&filler, 1, sizeof(filler), pFile);
fclose(pFile);
}
//Appending the audio sensor data to this .wav file
void write_pcm_data_to_file(char* inFile, char* outFile)
{
char buffer[SAMPLE_SIZE];
size_t n;
FILE *fin,*fout;
fin = fopen(inFile,"r");
fout = fopen(outFile,"a");
while((n = fread(buffer, 1, sizeof(buffer), fin)) > 0)
{
if(n != fwrite(buffer, 1, n, fout))
{
perror("fwrite");
exit(1);
}
}
fclose(fin);
fclose(fout);
}
This is how the resulting .wav file looks in hex editor:-
.wav file in hex editor
I can see that the wav header values are set correctly, followed by my PCM data from Audio Sensor.
However, when I play the .wav file, I am not able to play the input audio. Instead, I hear a constant tone.
I tried changing the input audio (played different music, songs), yet the resulting .wav file plays the same constant tone.
In order to recreate the input music played to the microphone into a wav file, what modifications should I do?
Thanks in advance.
Edit:-
According to 42LeapsOfFaith 's answer, to convert my samples to hex, I used the following code:-
hexValue = strtoll(sample, NULL, 16);
I converted each value in the buffer, then wrote it into my .wav file. Now my .wav file looks like modified .wav file in hex editor
However, even this wav file does not play the audio.
Any further suggestions to recreate the input music played to the microphone into a wav file?
Help is very much appreciated
For starters, you are storing the PCM data in the file as ascii-hex. I hope that helps.
This is a 'hack' you can use...
char c[2];
while((n = fread(&c[0], 2, 1, fin)) > 0)
{
if (c[0] > 0x39) c[0] -= 7;
c[0] &= 0x0F;
if (c[1] > 0x39) c[1] -= 7;
c[1] &= 0x0F;
c[1] |= c[0] << 4;
if(1 != fwrite(&c[1], 1, 1, fout))
I am trying to encode a PCM uncompressed Wav file using A law encoding.
I have written a function which takes in the 16 bit PCM data and returns 8 bit encoded data..After encoding, my file does not play properly..I feel that there is something I am not doing correctly to handle the files.I have separated the header information of the file and written the same header to output file.
// Code for compressing data is below
short inbuff;
unsigned char outbuff;
while (!feof(inp))
{
fread(inbuff, 2 , BUFSIZE, inp);
for (i=0; i < BUFSIZE; ++i)
{
temp_16 = inbuff[i];
temp_8 = Lin2Alaw(temp_16);
outbuff[i] = temp_8;
}
fwrite(outbuff, 1 , (BUFSIZE), out);
}
You are writing the data with the same header, which means that any audio program will think the data inside the WAV file is still PCM. Check the file format for WAV and change it accordingly.
Mainly you need to change audio format at 0x0014-0x0015 to a-law and other values also to mark the proper bytes per second, block size etc.
Easiest way to make sure they're correct might be to convert the file with an audio editor and then checking for the differences in the values.
How did your code even compile when you are not using arrays? Even so, your use of feof isn't good, please see Why is “while ( !feof (file) )” always wrong?
#include <stdio.h>
#define BUFSIZE 512
int main(void) {
short inbuff[BUFSIZE]; // must be an array
unsigned char outbuff[BUFSIZE]; // must be an array
size_t bread, i;
unsigned char temp_8;
short temp_16;
FILE *inp, *out;
// ... open the file
// ... transcribe the header
// rewrite the data
while ((bread = fread(inbuff, 2 , BUFSIZE, inp)) > 0)
{
for (i=0; i < bread; ++i) // only the data actually read
{
temp_16 = inbuff[i];
temp_8 = Lin2Alaw(temp_16);
outbuff[i] = temp_8;
}
fwrite(outbuff, 1 , bread, out); // only the data actually read
}
// ... finish off and close the file
return 0;
}
I notice too you are using signed short for the 16-bit data - should that be unsigned short?
See the format of wave file is at
http://www.topherlee.com/software/pcm-tut-wavformat.html
Now check all bytes of header and make sure all information about bit rate,sample rate etc are correct.
If your code for compressing is correct then issue should be with header file only.
I am trying to use libsndfile to write a multichannel wav that can be read by MATLAB 2010+.
the following code writes a 4 channel interleaved wav. all samples on channel 1 should be 0.1, on channel 2 they are 0.2, on channel 3 ... etc.
Each channel is 44100 samples in length.
I drag the wave file onto the MATLAB workspace and unfortunately MATLAB keeps returning "File contains uninterpretable data".
It may also be worth noting that when all samples are set to 0.0, MATLAB successfully reads the file, although very slowly.
I have successfully used libsndfile to read multichannel data written by MATLAB's wavwrite.m, so the library is setup up correctly I believe.
Audacity can read the resulting file from the code below.
VS 2012 64 bit compiler,
Win7 64bit, MATLAB 2015a
ref: the code has been adapted from http://www.labbookpages.co.uk/audio/wavFiles.html
Any suggestions, I presume i'm making a simple error here?
Thanks
#include <sndfile.h>
#include <stdio.h>
#include <stdlib.h>
int main()
{
// Create interleaved audio data
int numFrames_out = 44100;
int channels = 4;
float *int_y;
int_y = (float*)malloc(channels*numFrames_out*sizeof(float));
long q=0;
for (long i = 0; i<numFrames_out; i++)
{
for (int j = 0; j<channels; j++)
{
int_y[q+j] = ((float)(j+1))/10.0;
}
q+=channels;
}
// Set multichannel file settings
SF_INFO info;
info.format = SF_FORMAT_WAV | SF_FORMAT_PCM_32;
info.channels = channels;
info.samplerate = 44100;
// Open sound file for writing
char out_filename[] = "out_audio.wav";
SNDFILE *sndFile = sf_open(out_filename, SFM_WRITE, &info);
if (sndFile == NULL)
{
fprintf(stderr, "Error opening sound file '%s': %s\n", out_filename, sf_strerror(sndFile));
return -1;
}
// Write frames
long writtenFrames = sf_writef_float(sndFile, int_y, numFrames_out);
// Check correct number of frames saved
if (writtenFrames != numFrames_out) {
fprintf(stderr, "Did not write enough frames for source\n");
sf_close(sndFile);
free(int_y);
return -1;
}
sf_close (sndFile);
}
It looks like you are only closing the output file (using sf_close()) in the error case. The output file will not be a well formed WAV file unless you call sf_close() at the end of your program.
I want to test the compression and decompression functions: compress () uncompresss ()provides by the ZLIB library ; wrote the following code to open a file that already exists, read in a while () loop insidetake the contents of the file already exists, the compression portion write to a single file, the uncompress part written to another file, the code shown below, the size of the file that already exists (originalFile) about 78K , the first time to enter while() loop compression with decompression of the return value is 0, so that the first entry is successful, but the second and the next a few times to enter, return values are -5 (according to official documents, buffered output size is not large to contain the content), why ? Where was wrong? pre-thank you very much!
enter code here
#include <string>
#include <time.h>
#include <stdio.h>
#include <iostream>
#include <string.h>
#include "zlib.h"
int main()
{
unsigned long int fileLength;
unsigned long int readLength;
unsigned long int compressBufLength;
unsigned long int uncompressLength;
unsigned long int offset;
unsigned char *readBuf = new unsigned char[512];//the readbuf of the exist file content
unsigned char *compressBuf = new unsigned char[512];//the compress buffer
unsigned char *uncompressBuf = new unsigned char[512];//the uncompress content buffer
FILE *originalFile = fopen("/lgw150/temp/src/lg4/original.lg4","a+");//the exist file
FILE *compressedFile = fopen("/lgw150/temp/src/lg4/compressed.lg4","a+");//compressfile
FILE *uncompressFile = fopen("/lgw150/temp/src/lg4/uncompressed.lg4","a+");//
fseek(originalFile,0,2);
fileLength = ftell(originalFile);
offset = 0;//
while(offset <fileLength)//
{
printf("offset=%lu;fileLength=%lu\n",offset,fileLength);
memset(readBuf,0,512);
memset(compressBuf,0,512);
memset(uncompressBuf,0,512);
fseek(originalFile,offset,0);//
readLength = fread(readBuf,sizeof(char),512,originalFile);
offset += readLength;//
int compressValue = compress(compressBuf,&compressBufLength,readBuf,readLength);
int fwriteValue = fwrite(compressBuf,sizeof(char),compressBufLength,compressedFile);//
printf("compressValue = %d;fwriteLength = %d;compressBufLength=%lu;readLength = %lu\n",compressValue,fwriteValue,compressBufLength,readLength);
int uncompressValue = uncompress(uncompressBuf,&uncompressLength,compressBuf,compressBufLength);//
int fwriteValue2= fwrite(uncompressBuf,sizeof(char),uncompressLength,uncompressFile);//
}
fseek(originalFile,0,0);
fseek(compressedFile,0,0);
fseek(uncompressFile,0,0);
if(originalFile != NULL)
{
fclose(originalFile);
originalFile = NULL;
}
if(compressedFile != NULL)
{
fclose(compressedFile);
compressedFile = NULL;
}
if(uncompressFile != NULL)
{
fclose(uncompressFile);
uncompressFile = NULL;
}
delete[] readBuf;
delete[] compressBuf;
delete[] uncompressBuf;
return 0;
}
enter code here
First off, the reason you're getting "buffered output size is not large enough to contain the content" is because the buffered output size is not large enough to contain the content. If you give incompressible data to compress it will expand the data. So 512 bytes is not large enough if the input is 512 bytes. Use the compressBound() function for the maximum expansion for sizing the compression output buffer.
Second, compressing 512 bytes at a time is silly. You're not giving the compression algorithm enough data to work with in order to get the mileage you should be getting from the compression. Your application of reading 512 byte chunks at a time should not be using compress() and uncompress(). You should be using deflate() and inflate(), which were written for this purpose -- to feed chunks of data through the compression and decompression engines.
You need to read zlib.h. All of it. You can also look at the example (after reading zlib.h).
I have been building a simple samplerate converter in c using libsndfile and libsamplerate. I just cant seem to get the src_simple function of libsamplerate to work, whatever I try. I have striped back my code to be as simple as possible and it now just outputs a silent audio file of identical sampling rate:
#include <stdio.h>
#include <sndfile.h>
#include <samplerate.h>
#define BUFFER_LEN 1024
#define MAX_CHANNELS 6
int main ()
{
static double datain [BUFFER_LEN];
static double dataout [BUFFER_LEN];
SNDFILE *infile, *outfile;
SF_INFO sfinfo, sfinfo2 ;
int readcount ;
const char *infilename = "C:/Users/Oli/Desktop/MARTYTHM.wav" ;
const char *outfilename = "C:/Users/Oli/Desktop/Done.wav" ;
SRC_DATA src_data;
infile = sf_open (infilename, SFM_READ, &sfinfo);
outfile = sf_open (outfilename, SFM_WRITE, &sfinfo);
src_data.data_in = datain
src_data.input_frames = BUFFER_LEN;
src_data.data_out = dataout;
src_data.output_frames = BUFFER_LEN;
src_data.src_ratio = 0.5;
src_simple (&src_data, SRC_SINC_BEST_QUALITY, 1);
while ((readcount = sf_read_double (infile, datain, BUFFER_LEN)))
{
src_simple (&src_data, SRC_SINC_BEST_QUALITY, 1);
sf_write_double (outfile, dataout, readcount) ;
};
sf_close (infile);
sf_close (outfile);
sf_open ("C:/Users/Oli/Desktop/Done.wav", SFM_READ, &sfinfo2);
printf("%d", sfinfo2.samplerate);
return 0;
}
It's really starting to stress me out. The program is a uni project and is due very soon, it is making me very anxious as whatever I try seems to result in failure. Can anyone please help me?
I'm not an expert on this particular library, but just from looking at the online documentation I see a few problems with your code:
src_simple apparently works with floats, yet your buffers are doubles - I think you need to change the buffers to float and use sf_read_float/sf_write_float for I/O.
src_simple is the "simple" interface and is intended to be applied to an entire waveform in one call, not in chunks as you are doing - see http://www.mega-nerd.com/SRC/faq.html#Q004 - you should first get the input file size, then allocate sufficient memory, read in the whole file, convert it in one go, then write the converted output data to your output file.
when changing sample rate you will get a different number of samples in the output file than in the output file (around half as many in for case), yet you're writing the same number of samples that you read (readcount). You should probably be using src_data.output_frames_gen as the number of frames to write, not readcount.