Create Vi to Read .wav File Chegg

The WAV (or PCM) audio format is the near basic format for storing audio. WAV files can be of dissimilar extended formats , only PCM is the most pop and common. The other formats are A-law and Mu-law. The PCM format stores raw audio data without any compression or conversion, thus leading to the largest file sizes, equally compared to other formats like AIFF or MP3 or OGG.

While there are existing libraries in several languages which allow you to work with WAV files, this post is an endeavor to understand how to read the WAV file format without any external library. The language used here is C, and has been compiled using GCC under Linux, but it can be hands run under Windows also with minimal modifications. Most probable for VC++ you will have to replace #include <unistd.h> with #include <io.h>

WAV HEADER Structure

The header structure is 44 bytes long and has the following structure:

Positions Sample Value Description
1 – 4 "RIFF" Marks the file as a riff file. Characters are each 1 byte long.
five – 8 File size (integer) Size of the overall file – 8 bytes, in bytes (32-flake integer). Typically, y'all'd make full this in after creation.
9 -12 "Wave" File Type Header. For our purposes, it ever equals "Wave".
13-16 "fmt " Format chunk marker. Includes abaft zilch
17-20 xvi Length of format data as listed above
21-22 1 Type of format (1 is PCM) – 2 byte integer
23-24 2 Number of Channels – 2 byte integer
25-28 44100 Sample Rate – 32 byte integer. Mutual values are 44100 (CD), 48000 (DAT). Sample Rate = Number of Samples per second, or Hertz.
29-32 176400 (Sample Rate * BitsPerSample * Channels) / 8.
33-34 4 (BitsPerSample * Channels) / 8.1 – viii chip mono2 – 8 bit stereo/xvi scrap mono4 – 16 bit stereo
35-36 xvi Bits per sample
37-40 "data" "data" chunk header. Marks the beginning of the data department.
41-44 File size (data) Size of the data department.
Sample values are given in a higher place for a 16-bit stereo source.

It is important to note that the WAV  format uses little-endian format to store bytes, then you need to convert the bytes to large-endian in code for the values to make sense.

EDIT: AUG 2020

Thanks to a problems pointed out by Kalpathi Subramanian, the lawmaking has been updated to rectify the bug. He has adapted this lawmaking into a C++ implementation which is available on https://github.com/BridgesUNCC/bridges-cxx/blob/master/src/AudioClip.h

Lawmaking

The code consists of a header file wave.h which is included in wave.c . Once yous compile it and run it, it accepts the path of a wav file from the command line and dumps the structure information including the size of each sample and the total duration of the wav audio.

wave.h

// Wave file header format struct HEADER { 	unsigned char riff[iv];						// RIFF string 	unsigned int overall_size	;				// overall size of file in bytes 	unsigned char wave[4];						// WAVE string 	unsigned char fmt_chunk_marker[4];			// fmt string with trailing null char 	unsigned int length_of_fmt;					// length of the format data 	unsigned int format_type;					// format type. ane-PCM, 3- IEEE float, half-dozen - 8bit A law, 7 - 8bit mu law 	unsigned int channels;						// no.of channels 	unsigned int sample_rate;					// sampling rate (blocks per second) 	unsigned int byterate;						// SampleRate * NumChannels * BitsPerSample/8 	unsigned int block_align;					// NumChannels * BitsPerSample/8 	unsigned int bits_per_sample;				// bits per sample, 8- 8bits, sixteen- 16 bits etc 	unsigned char data_chunk_header [4];		// DATA cord or FLLR cord 	unsigned int data_size;						// NumSamples * NumChannels * BitsPerSample/8 - size of the next clamper that will exist read };          

moving ridge.c

/**  * Read and parse a wave file  *  **/ #include <unistd.h> #include <stdio.h> #include <string.h> #include <stdlib.h> #include "moving ridge.h" #define Truthful one  #define Faux 0  // Moving ridge header construction  unsigned char buffer4[four]; unsigned char buffer2[2];  char* seconds_to_time(float seconds);    FILE *ptr;  char *filename;  struct HEADER header;  int main(int argc, char **argv) {   filename = (char*) malloc(sizeof(char) * 1024);  if (filename == Zero) {    printf("Fault in mallocn");    exit(one);  }   // become file path  char cwd[1024];  if (getcwd(cwd, sizeof(cwd)) != NULL) {     	strcpy(filename, cwd);  	// get filename from command line 	if (argc < 2) { 	  printf("No wave file specifiedn"); 	  render; 	} 	 	strcat(filename, "/"); 	strcat(filename, argv[1]); 	printf("%sn", filename);  }   // open file  printf("Opening  file..due north");  ptr = fopen(filename, "rb");  if (ptr == NULL) { 	printf("Error opening filen"); 	exit(i);  }    int read = 0;    // read header parts   read = fread(header.riff, sizeof(header.riff), 1, ptr);  printf("(i-4): %s northward", header.riff);    read = fread(buffer4, sizeof(buffer4), ane, ptr);  printf("%u %u %u %un", buffer4[0], buffer4[1], buffer4[ii], buffer4[3]);    // convert fiddling endian to big endian 4 byte int  header.overall_size  = buffer4[0] |  						(buffer4[1]<<8) |  						(buffer4[ii]<<16) |  						(buffer4[3]<<24);   printf("(five-8) Overall size: bytes:%u, Kb:%u due north", header.overall_size, header.overall_size/1024);   read = fread(header.moving ridge, sizeof(header.wave), 1, ptr);  printf("(9-12) Wave marker: %sn", header.moving ridge);   read = fread(header.fmt_chunk_marker, sizeof(header.fmt_chunk_marker), 1, ptr);  printf("(13-16) Fmt marker: %sn", header.fmt_chunk_marker);   read = fread(buffer4, sizeof(buffer4), 1, ptr);  printf("%u %u %u %un", buffer4[0], buffer4[1], buffer4[2], buffer4[3]);   // catechumen little endian to big endian 4 byte integer  header.length_of_fmt = buffer4[0] | 							(buffer4[one] << 8) | 							(buffer4[2] << 16) | 							(buffer4[3] << 24);  printf("(17-xx) Length of Fmt header: %u northward", header.length_of_fmt);   read = fread(buffer2, sizeof(buffer2), 1, ptr); printf("%u %u due north", buffer2[0], buffer2[1]);    header.format_type = buffer2[0] | (buffer2[1] << 8);  char format_name[ten] = "";  if (header.format_type == ane)    strcpy(format_name,"PCM");   else if (header.format_type == 6)   strcpy(format_name, "A-police");  else if (header.format_type == 7)   strcpy(format_name, "Mu-law");   printf("(21-22) Format type: %u %s n", header.format_type, format_name);   read = fread(buffer2, sizeof(buffer2), 1, ptr);  printf("%u %u n", buffer2[0], buffer2[1]);   header.channels = buffer2[0] | (buffer2[ane] << 8);  printf("(23-24) Channels: %u n", header.channels);   read = fread(buffer4, sizeof(buffer4), 1, ptr);  printf("%u %u %u %un", buffer4[0], buffer4[1], buffer4[2], buffer4[3]);   header.sample_rate = buffer4[0] | 						(buffer4[one] << 8) | 						(buffer4[2] << xvi) | 						(buffer4[three] << 24);   printf("(25-28) Sample charge per unit: %un", header.sample_rate);   read = fread(buffer4, sizeof(buffer4), one, ptr);  printf("%u %u %u %un", buffer4[0], buffer4[one], buffer4[2], buffer4[3]);   header.byterate  = buffer4[0] | 						(buffer4[one] << eight) | 						(buffer4[2] << xvi) | 						(buffer4[3] << 24);  printf("(29-32) Byte Rate: %u , Chip Rate:%un", header.byterate, header.byterate*8);   read = fread(buffer2, sizeof(buffer2), 1, ptr);  printf("%u %u n", buffer2[0], buffer2[1]);   header.block_align = buffer2[0] | 					(buffer2[1] << viii);  printf("(33-34) Block Alignment: %u due north", header.block_align);   read = fread(buffer2, sizeof(buffer2), 1, ptr);  printf("%u %u northward", buffer2[0], buffer2[1]);   header.bits_per_sample = buffer2[0] | 					(buffer2[i] << 8);  printf("(35-36) Bits per sample: %u northward", header.bits_per_sample);   read = fread(header.data_chunk_header, sizeof(header.data_chunk_header), 1, ptr);  printf("(37-40) Data Marking: %s n", header.data_chunk_header);   read = fread(buffer4, sizeof(buffer4), 1, ptr);  printf("%u %u %u %un", buffer4[0], buffer4[1], buffer4[2], buffer4[three]);   header.data_size = buffer4[0] | 				(buffer4[i] << 8) | 				(buffer4[ii] << 16) |  				(buffer4[three] << 24 );  printf("(41-44) Size of data chunk: %u north", header.data_size);    // calculate no.of samples  long num_samples = (8 * header.data_size) / (header.channels * header.bits_per_sample);  printf("Number of samples:%lu n", num_samples);   long size_of_each_sample = (header.channels * header.bits_per_sample) / viii;  printf("Size of each sample:%ld bytesn", size_of_each_sample);   // calculate duration of file  float duration_in_seconds = (bladder) header.overall_size / header.byterate;  printf("Approx.Duration in seconds=%fn", duration_in_seconds);  printf("Approx.Duration in h:m:s=%sn", seconds_to_time(duration_in_seconds));     // read each sample from information chunk if PCM  if (header.format_type == i) { // PCM     printf("Dump sample information? Y/N?"); 	char c = 'due north'; 	scanf("%c", &c); 	if (c == 'Y' || c == 'y') {  		long i =0; 		char data_buffer[size_of_each_sample]; 		int  size_is_correct = TRUE;  		// brand sure that the bytes-per-sample is completely divisible past num.of channels 		long bytes_in_each_channel = (size_of_each_sample / header.channels); 		if ((bytes_in_each_channel  * header.channels) != size_of_each_sample) { 			printf("Error: %ld x %ud <> %ldn", bytes_in_each_channel, header.channels, size_of_each_sample); 			size_is_correct = FALSE; 		}   		if (size_is_correct) {  					// the valid amplitude range for values based on the bits per sample 			long low_limit = 0l; 			long high_limit = 0l;  			switch (header.bits_per_sample) { 				case eight: 					low_limit = -128; 					high_limit = 127; 					break; 				instance xvi: 					low_limit = -32768; 					high_limit = 32767; 					pause; 				case 32: 					low_limit = -2147483648; 					high_limit = 2147483647; 					intermission; 			}					  			printf("nn.Valid range for data values : %ld to %ld n", low_limit, high_limit); 			for (i =1; i <= num_samples; i++) { 				printf("==========Sample %ld / %ld=============n", i, num_samples); 				read = fread(data_buffer, sizeof(data_buffer), 1, ptr); 				if (read == 1) { 				 					// dump the data read 					unsigned int  xchannels = 0; 					int data_in_channel = 0; 					int get-go = 0; // move the offset for every iteration in the loop below 					for (xchannels = 0; xchannels < header.channels; xchannels ++ ) { 						printf("Channel#%d : ", (xchannels+1)); 						// convert information from little endian to large endian based on bytes in each channel sample 						if (bytes_in_each_channel == four) { 							data_in_channel = (data_buffer[offset] & 0x00ff) |  												((data_buffer[outset + i] & 0x00ff) <<8) |  												((data_buffer[offset + 2] & 0x00ff) <<16) |  												(data_buffer[start + 3]<<24); 						} 						else if (bytes_in_each_channel == ii) { 							data_in_channel = (data_buffer[offset] & 0x00ff) | 												(data_buffer[first + one] << viii); 						} 						else if (bytes_in_each_channel == ane) { 							data_in_channel = data_buffer[offset] & 0x00ff; 							data_in_channel -= 128; //in wave, eight-bit are unsigned, so shifting to signed 						}  						kickoff += bytes_in_each_channel;		 						printf("%d ", data_in_channel);  						// cheque if value was in range 						if (data_in_channel < low_limit || data_in_channel > high_limit) 							printf("**value out of rangen");  						printf(" | "); 					}  					printf("due north"); 				} 				else { 					printf("Error reading file. %d bytesn", read); 					break; 				}  			} // 	for (i =1; i <= num_samples; i++) {  		} // 	if (size_is_correct) {   	 } // if (c == 'Y' || c == 'y') {   } //  if (header.format_type == 1) {    printf("Closing file..north");  fclose(ptr);    // cleanup before quitting  costless(filename);  return 0;  }  /**  * Convert seconds into hh:mm:ss format  * Params:  *	seconds - seconds value  * Returns: hms - formatted string  **/  char* seconds_to_time(bladder raw_seconds) {   char *hms;   int hours, hours_residue, minutes, seconds, milliseconds;   hms = (char*) malloc(100);    sprintf(hms, "%f", raw_seconds);    hours = (int) raw_seconds/3600;   hours_residue = (int) raw_seconds % 3600;   minutes = hours_residue/60;   seconds = hours_residue % 60;   milliseconds = 0;    // get the decimal part of raw_seconds to get milliseconds   char *pos;   pos = strchr(hms, '.');   int ipos = (int) (pos - hms);   char decimalpart[15];   memset(decimalpart, ' ', sizeof(decimalpart));   strncpy(decimalpart, &hms[ipos+ane], 3);   milliseconds = atoi(decimalpart);	       sprintf(hms, "%d:%d:%d.%d", hours, minutes, seconds, milliseconds);   render hms; }          

A sample run is given beneath:

Screenshot from 2015-09-05 19:29:20

farmerloctionly.blogspot.com

Source: http://truelogic.org/wordpress/2015/09/04/parsing-a-wav-file-in-c/

0 Response to "Create Vi to Read .wav File Chegg"

Post a Comment

Iklan Atas Artikel

Iklan Tengah Artikel 1

Iklan Tengah Artikel 2

Iklan Bawah Artikel