How to Read Wav File in C

C Language resolution WAV audio file code accost: Github:github.com/casterwx/c-moving ridge-main Directory

    • Objective
    • Understanding WAV Audio Files
    • What is a binary file
    • Binary format parsing of WAV
    • C linguistic communication parsing WAV audio files
    • Two details
    • Summarize

In the calculator has a variety of files, such as EXE executable file, jpg This image file, nosotros usually encounter the TXT, or c,cpp,php and other code files.

If you open up these files in Notepad or other plain text editor, y'all will find that the previous type of file is basically garbled after opening, that is, non-human readable characters, and later such code or TXT file opened is a homo readable string.

If we make a nomenclature of these files, so the exe,jpg, such equally the preceding one, is a file that nosotros can non empathise the outer planet text, which is called a binary file, and the latter file is called a text file.

The latter kind of classification is a adept understanding of text files, after all, we know the text, but the front of those garbled why call him a binary file? How these binary files are recognized by the computer, why these garbled can be recognized by the computer, and to release melodious music or lifelike pictures? We larn programming, computer-making people can also write a plan to translate the data out? Please listen to this column of pigs slowly.

Objective

We'll have a stride-past-step look at some of the basic library uses of C, and how to use these libraries to parse an audio file in WAV format and excerpt the metadata (that is, some of the backdrop of the audio file). So y'all need to have basic computer fundamentals and understand the C language, preferably with an interest in audio or indicate processing.

Agreement WAV Sound Files

Here is the caption of Baidu Encyclopedia

WAV is a audio file format developed by Microsoft Corporation (Microsoft) that complies with the riff (Resources Interchange File format) files specification for saving audio information resource for the Windows platform. Widely supported past the Windows platform and its applications, this format also supports a diversity of pinch algorithms such as Msadpcm,ccitt A Law, supports a diverseness of sound numbers, sampling frequency and channels, standard formatted WAV files and CD formats, Also 44.1K sampling frequency, 16-chip quantization number, then the sound file quality and CD-Like! The WAV Open tool is a media actor for Windows.
Typically iii parameters are used to represent sound, quantify the number of $.25, sample frequency, and sample point amplitude. Quantization bits are divided into 8-chip, 16-chip, 24-fleck, three-channel channels with mono and stereo, mono-amplitude data of n1 matrix points, stereo ntwo matrix points, sampling frequency 11025Hz (11kHz), 22050Hz (22kHz) and 44100Hz ( 44KHZ) three kinds, but despite the excellent sound quality, the compressed file size is too large! Relative to other audio formats is a disadvantage, its file size is calculated every bit: WAV format file occupied chapters (B) = (sampling frequency x quantization digit x aqueduct) ten Time/8 (byte = 8bit) each infinitesimal the size of the WAV format audio file is 10MB, its size does non vary with the book size and sharpness and change.

We usually download songs in a multifariousness of music players volition run into a diversity of parameters, such as the normal quality of the stream is 128k, high quality is 320k, and lossless Ape,flac and other formats. There are likewise times when we encounter diverse parameters, such as sample rate, quantization accuracy, and whether the sound file is mono or stereo, and and so on, using various sound format conversion tools.

We are now listening to MP3 format music, WAV now in add-on to the Windows recorder, at that place is basically no place to employ, why still use him to exercise the example? This is because WAV is substantially an uncompressed raw audio file, and his file structure is not very complex, so it can be used every bit a learning sample format for our beginners. Yous can follow the aforementioned thought to learn other formats yourself.

What is a binary file

Binary files, essentially a file that uses binary ways to store the contents of files collectively, we take said before using Notepad and other tools to come across is garbled, then how we analyze him, you can use Ultraeditor,hxd,c32asm and so on. For example, I'm using HxD to turn off music for Windows seven (C:\Windows\Media\Windows Shutdown.wav) This way, on the left is the binary representation of this WAV audio file, and the right side is the ASCII representation of the binary number, since numbers like 00 are non shown in ASCII, then the right side of the interface is a point. And what do the numbers on the left side of these 52,49 stand for to? In fact, these binary numbers appear garbled, in fact, at that place are certain specifications, every bit long as we or our estimator to a higher place the awarding to understand this specification, you can follow this specification to interpret it.

Binary format parsing of WAV

According to diverse information on the network, the wave file is substantially a riff format, which tin be bathetic into a tree (a kind of data structure).

We see this graph in a higher place, which corresponds to the offset of the binary information in the file relative to the starting position, from height to bottom respectively. Each grid corresponds to a field, field size represents the size of each field, and depending on the size and electric current offset, we tin can also calculate the starting address (offset) of the next field.

Next, let's explain what each of the above fields ways. According to Riff's specification, the top chunk of the entire WAV file is the chunkid riff of this chunk, which can also explain why we tin see in the previous picture that the WAV file starts with a few letters riff. The next chunksize is the size of the chunk under the clamper, and if information technology is understood by "tree construction", then each child chunk (subchunk) is a tree branch. The format is the actual data for this chunk.

Frankly, a chunk structure is actually iii parts, the first part of the identifier is used to illustrate what the chunk is, the second part is how much of this chunk content, for the program to know if you want to find the adjacent clamper the address commencement how much to read, And the 3rd part is the actual content.

All right, let's finish the top clamper, we'll take a look. Chunk, the beginning clamper subchunk1id in a WAV file is a constant FMT, indicating that the content of the subchunk is some metadata of the WAV audio file, that is, some format information of the WAV audio. For example, audioformat This field is typically 1, indicating that the WAV sound is encoded as PCM. The numchannels is the number of channels for the WAV sound file. The samplerate is the sampling rate and the byterate is the sampling rate. Blockalign is the average size of each block, which equals numchannels * bitspersample/8, as to what the block is, and how its adding formula is derived to look at some other subchunk. The bitspersample is sampled bits per second, some of which are called quantization accuracy or PCM bit width. (not in the elegant)

Another sub-chunk is subchunk2id is in the WAV file abiding information, that is, the WAV audio file of the actual sound data, said the professional bespeak, which is stored in the audio sample information. Just if our audio is two-aqueduct, then the data sampled at ane sampling time is actually composed of the left and right channels. And this co-composed sample we made him a cake. In front of the Blockalign = Numchannels * BITSPERSAMPLE/8, this is now very well understood, every bit to why the stop is divided by viii, this is because the computer is a eight binary number represents a byte, so separate past 8来 to observe the number of bytes.

As for the length of the audio, we can split up by Subchunk2size by Byterate, that is, the full length of the chunk of the actual sound data divided by the number of bytes per 2d to how many seconds.

C language parsing WAV audio files

In front of then many, now the problem, how to plan to achieve the estimation of the above mentioned meta-information. C language Basic binary file operation function has Fopen,fread and and then on. (Note that information technology is a binary file performance part, so nosotros do not discuss fgets, this is the normal text file operation function)

Fread is a office. Reads information from a file stream, reading upward to count entries, each item of size bytes, if the telephone call succeeds in returning the number of entries really read to (less than or equal to count), and returns 0 if it is unsuccessful or read to the end of the file.

Its function image is

            
size_t fread ( void *buffer, size_t size, size_t count, FILE *stream) ;

And the C language has a type chosen struct, which is stored sequentially in memory. Only equally we have learned the guild of the WAV file in the file and the meaning of each part in that order, nosotros tin can ascertain the skilful one struct in advance according to the previous WAV file structure, and so initialize the struct in main function. And with the first parameter of fread into the initialized struct, the file is automatically read later on execution, and the metadata is automatically populated into our initialized struct in lodge. Nosotros can have these metadata direct from the struct.

The code is as follows:

Wave.c

            
#include <stdio.h>  #include <stdint.h>  #include <stdlib.h>  #include "wave.h"  int main()  {     FILE *fp = NULL;           Wav wav;      RIFF_t riff;      FMT_t fmt;      Data_t data;        fp = fopen("examination.wav", "rb");      if (!fp) {          printf("tin can't open audio file\north");          leave(1);      }        fread(&wav, ane, sizeof(wav), fp);            riff = wav.riff;      fmt = wav.fmt;      data = wav.information;        printf("ChunkID \t%c%c%c%c\n", riff.ChunkID[0], riff.ChunkID[1], riff.ChunkID[ii], riff.ChunkID[3]);      printf("ChunkSize \t%d\n", riff.ChunkSize);      printf("Format \t\t%c%c%c%c\northward", riff.Format[0], riff.Format[1], riff.Format[ii], riff.Format[3]);            printf("\north");            printf("Subchunk1ID \t%c%c%c%c\north", fmt.Subchunk1ID[0], fmt.Subchunk1ID[1], fmt.Subchunk1ID[2], fmt.Subchunk1ID[3]);      printf("Subchunk1Size \t%d\north", fmt.Subchunk1Size);      printf("AudioFormat \t%d\n", fmt.AudioFormat);      printf("NumChannels \t%d\n", fmt.NumChannels);      printf("SampleRate \t%d\n", fmt.SampleRate);      printf("ByteRate \t%d\n", fmt.ByteRate);      printf("BlockAlign \t%d\due north", fmt.BlockAlign);      printf("BitsPerSample \t%d\n", fmt.BitsPerSample);            printf("\n");        printf("blockID \t%c%c%c%c\n", data.Subchunk2ID[0], data.Subchunk2ID[1], data.Subchunk2ID[2], data.Subchunk2ID[3]);      printf("blockSize \t%d\n", data.Subchunk2Size);            printf("\n");           printf("duration \t%d\northward", data.Subchunk2Size / fmt.ByteRate);  }

Moving ridge.h

            
typedef struct WAV_RIFF {     /* clamper "riff" */     char ChunkID[4];   /* "RIFF" */     /* sub-chunk-size */     uint32_t ChunkSize; /* 36 + Subchunk2Size */     /* sub-chunk-information */     char Format[4];    /* "Moving ridge" */ } RIFF_t;  typedef struct WAV_FMT {     /* sub-chunk "fmt" */     char Subchunk1ID[4];   /* "fmt " */     /* sub-chunk-size */     uint32_t Subchunk1Size; /* sixteen for PCM */     /* sub-chunk-data */     uint16_t AudioFormat;   /* PCM = 1*/     uint16_t NumChannels;   /* Mono = 1, Stereo = 2, etc. */     uint32_t SampleRate;    /* 8000, 44100, etc. */     uint32_t ByteRate;  /* = SampleRate * NumChannels * BitsPerSample/8 */     uint16_t BlockAlign;    /* = NumChannels * BitsPerSample/8 */     uint16_t BitsPerSample; /* 8bits, 16bits, etc. */ } FMT_t;  typedef struct WAV_data {     /* sub-chunk "data" */     char Subchunk2ID[iv];   /* "data" */     /* sub-chunk-size */     uint32_t Subchunk2Size; /* data size */     /* sub-chunk-data */ //    Data_block_t block; } Data_t;  //typedef struct WAV_data_block { //} Data_block_t;  typedef struct WAV_fotmat {    RIFF_t riff;    FMT_t fmt;    Data_t information; } Wav;

Execution results

Two details

1, fopen when our mode to be set up to "RB", R indicates that read,b represents binary, that is, binary read mode. This is somewhat different from reading the traditional text file format.

2, the struct type inside I use is the uint32_t and and so on the type, only is not the traditional int,brusque and so on, this is in order to consider the unlike compiler, dissimilar platform for the int blazon allocates the memory infinite inconsistency question. These types are provided past the Stdint.h header file, so we need to import it on the head.

Summarize

In fact, any binary information has its own parsing specifications, which is a bit like when nosotros learn the computer network when the "Protocol", as long as nosotros follow this specification or "protocol", and then we tin be the file actually hidden information read out.

We merely read a WAV audio file in the meta-data, non to its information clamper, that is, the bodily sound of the digital signal read out, because this involves the conversion of digital mode indicate and other knowledge, beyond the scope of our enquiry,

Alibaba Deject Hot Products

Rubberband Compute Service (ECS) Dedicated Host (DDH) ApsaraDB RDS for MySQL (RDS) ApsaraDB for PolarDB(PolarDB) AnalyticDB for PostgreSQL (ADB for PG)
AnalyticDB for MySQL(ADB for MySQL) Data Transmission Service (DTS) Server Load Balancer (SLB) Global Accelerator (GA) Cloud Enterprise Network (CEN)
Object Storage Service (OSS) Content Delivery Network (CDN) Short Message Service (SMS) Container Service for Kubernetes (ACK) Data Lake Analytics (DLA)

ApsaraDB for Redis (Redis)

ApsaraDB for MongoDB (MongoDB) NAT Gateway VPN Gateway Cloud Firewall
Anti-DDoS Web Awarding Firewall (WAF) Log Service DataWorks MaxCompute
Elastic MapReduce (EMR) Elasticsearch

Alibaba Cloud Free Trail

metcalfthervice.blogspot.com

Source: https://topic.alibabacloud.com/a/c-language-parsing-wav-audio-files_1_31_30000716.html

Related Posts

0 Response to "How to Read Wav File in C"

Post a Comment

Iklan Atas Artikel

Iklan Tengah Artikel 1

Iklan Tengah Artikel 2

Iklan Bawah Artikel