Android Audio Development (4): How to store and parse WAV files

Source: Internet
Author: User

Whether it is text, image or sound, must be organized and stored in a certain format, so that the player will know how to parse this piece of data, for example, for the original image data, our common format is YUV, Bitmap, and for audio, the simplest common format is the WAV format.


WAV format, like bitmap, are Microsoft developed a file format specification, they all have a similarity, is the whole file is divided into two parts, the first part is "File header", record important parameter information, for audio, including: sample rate, number of channels, bit width, etc. For the image, it includes: the width of the image, the number of color digits, and so on; the second part is "Data Block", that is, one frame of binary data, for audio, is the original PCM data, for the image, is the RGB data.


The previous articles on how to use the Android platform API to complete the acquisition and playback of raw audio signals, and this article focuses on how to save the captured PCM audio data to WAV files on the Android platform, but also describes how to read and parse WAV files.


And at the end of the article, I'll give you a Audiodemo program that combines the code of recent articles with the entire process of capturing and playing a complete Android audio.


Let's talk about how to read and write WAV file format.


1. File header


First, we understand the WAV format "file header", you can refer to this article: "WAVE PCM soundfile format"


650) this.width=650; "src=" Http://s4.51cto.com/wyfs02/M00/7D/AD/wKioL1btPw_xefJSAABiQscQxNA841.png "title=" F98ff8fa-cfea-4256-ae5a-26ef797f8cba.png "alt=" Wkiol1btpw_xefjsaabiqscqxna841.png "/>


We can simply analyze this WAV format header, which is divided into three parts:


The first part, belonging to the most "top-level" of the information block, through "chunkid" to indicate that this is a "RIFF" format of the file, through "format" filled "WAVE" to identify this is a WAV file. The "ChunkSize" records the number of bytes for the entire WAV file.


The second part, belonging to the "FMT" information block, mainly recorded in this WAV audio file detailed audio parameter information, such as: Channel number, sample rate, bit width and so on (meaning please refer to my first article "Android Audio Development (1): basic knowledge")


The third part, belongs to "data" information block, the "subchunk2size" this field to record the length of the binary raw audio data stored later.


Analysis here, I think we should understand, in fact, do a multimedia format parsing, is not a particularly complex thing, plainly, the format is a specification, tell you, my binary data is how to store, you should follow what kind of way to parse.


Specifically, we can define a Java class as follows to abstract and describe the WAV file header:


/* *  copyright notice   *  copyright  (C)  2016,  jhuster <lu[email protected]> *  https://github.com/jhuster/audiodemo *     *   @license  under the Apache License, Version  2.0  * *   @file     wavfileheader.java *   *    @version  1.0      *   @author   Jhuster  *   @date     2016/03/19 */package com.jhuster.audiodemo.api;public  class wavfileheader {           public  String mChunkID =  "RIFF";     public int mchunksize =  0;        public String mFormat =  "WAVE";     public string msubchunk1id =  "fmt ";    public int  msubchunk1size = 16;    public short maudioformat = 1;         public short mNumChannel = 1;     public int msamplerate = 8000;    public int mbyterate  = 0;    public short mBlockAlign = 0;     public short mBitsPerSample = 8;    public String  msubchunk2id =  "Data";    public int msubchunk2size  =  0;        public wavfileheader ()  {             }        public  Wavfileheader (Int samplerAteinhz, int bitspersample, int channels)  {                   mSampleRate = sampleRateInHz;         mBitsPerSample =  (short) bitspersample;         mNumChannel =  (short) channels;                          mByteRate = mSampleRate*mNumChannel*mBitsPerSample/8;         mBlockAlign =  (short) (MNUMCHANNEL*MBITSPERSAMPLE/8);     }}


The meaning of each of the fields, you can refer to the link I gave above, let's look at how to read and write WAV file.


2. Read and write WAV files


The beginning of the article has said, in fact, the WAV file is a "file header" + "Audio binary data", so:


(1) Write WAV file, actually write a WAV file header first, and then continue to write audio binary data can be

(2) Read WAV file, in fact, read a WAV file first, and then continue to read the audio binary data can be


Well, before you write the code, there are two points you need to figure out:


(1) WAV file header, what is "changing", which is "unchanged"?


For example: the "RIFF" string at the beginning of the file header is the "unchanging" part, while the "subchunk2size" variable used to record the total length of the audio data is the "changing" part, because you cannot know how many bytes of audio data are written until the audio data is completely written. , so this part needs to be recorded with a variable, and after all is written, use Java's "Randomaccessfile" class to jump the file pointer to the "Subchunk2size" field, overwriting the default value.


(2) How to convert an int, short variable and byte[]


Because WAV files are read and written in binary mode, the variables defined in the "Wavfileheader" class need to be converted to byte streams, as follows:


private static byte[] Inttobytearray (int data) {return Bytebuffer.allocate (4). Order (Byteorder.little_endian). Putint ( data). Array ();} private static byte[] Shorttobytearray (short data) {return bytebuffer.allocate (2). Order (Byteorder.little_endian). Putshort (data). Array ();} private static short Bytearraytoshort (byte[] b) {return bytebuffer.wrap (b). Order (Byteorder.little_endian). Getshort ()    ;} private static int bytearraytoint (byte[] b) {return bytebuffer.wrap (b). Order (Byteorder.little_endian). GetInt ();


About WAV file read and write Class I have helped everyone "encapsulation" well, and combined with the previous several articles given the audio collection and playback of the code, completed a Audiodemo program, put on my Github, welcome to download Run test, and then combine the code specific learning Android Audio-related technology, code address:


Https://github.com/Jhuster/AudioDemo


Note: All code for this series of articles will be incorporated into the demo project in the future.


3. Summary


about how to read and write WAV format files on the Android platform is introduced here, the article is not clear of the place to welcome messages or letters [email protected] exchange, or follow my Sina Weibo @ Lu _ June or the public number @Jhuster to obtain the latest articles and information.

650) this.width=650; "src=" http://s1.51cto.com/wyfs02/M01/7D/B1/wKiom1btRXCw5NW_AACb8XAe6Uo420.jpg "title=" Weixin _jhuster.jpg "alt=" Wkiom1btrxcw5nw_aacb8xae6uo420.jpg "/>

This article is from the "jhuster column" blog, be sure to keep this source http://ticktick.blog.51cto.com/823160/1752947

Android Audio Development (4): How to store and parse WAV files

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.