Android uses AudioRecord recording-related and audio file Encapsulation

Source: Internet
Author: User

 

MediaRecord can be used for recording in Android, which is easy to operate. However, it is not professional enough to Process audio. If you want to process audio in real time or encapsulate the audio

 

You can use AudioRecord for recording.

 

Here is a piece of code. Audio Recording in AudioRecord and audio encapsulation in WAV format are implemented.

 

AudioTrack and AudioTrack can be used for edge recording and play, you can refer to: http://www.bkjia.com/kf/201112/113210.html

 

The code here is not played. But there are encapsulation and details, as follows:

 

Package com. ppmeet;

 

Import java. io. File;

Import java. io. FileInputStream;

Import java. io. FileNotFoundException;

Import java. io. FileOutputStream;

Import java. io. IOException;

Import android. app. Activity;

Import android. graphics. PixelFormat;

Import android. media. AudioFormat;

Import android. media. AudioRecord;

Import android. media. MediaRecorder;

Import android. OS. Bundle;

Import android. view. View;

Import android. view. View. OnClickListener;

Import android. view. Window;

Import android. view. WindowManager;

Import android. widget. Button;

 

/**

* Class name: TestAudioRecord <BR>

* Class description: Use AudioRecord for recording <BR>

* PS: <BR>

*

* @ Version 1.00

* @ Author CODYY) peijiangping

*/

Public class TestAudioRecord extends Activity {

// Obtain the audio source

Private int audioSource = MediaRecorder. AudioSource. MIC;

// Set the audio sampling rate. 44100 is the current standard, but some devices still support 11025

Private static int sampleRateInHz = 44100;

// Set the audio recording channel CHANNEL_IN_STEREO to dual-channel and CHANNEL_CONFIGURATION_MONO to single-channel.

Private static int channelConfig = AudioFormat. CHANNEL_IN_STEREO;

// Audio Data Format: PCM 16-bit each sample. Ensure device support. PCM 8-bit each sample. Not necessarily supported by devices.

Private static int audioFormat = AudioFormat. ENCODING_PCM_16BIT;

// Buffer byte size: www.2cto.com

Private int bufferSizeInBytes = 0;

Private Button Start;

Private Button Stop;

Private AudioRecord audioRecord;

Private boolean isRecord = false; // you can specify the recording status.

// AudioName raw audio data file

Private static final String AudioName = "/sdcard/love. raw ";

// NewAudioName audio files that can be played

Private static final String NewAudioName = "/sdcard/new.wav ";

 

Public void onCreate (Bundle savedInstanceState ){

Super. onCreate (savedInstanceState );

GetWindow (). setFormat (PixelFormat. TRANSLUCENT); // Landscape Display

RequestWindowFeature (Window. FEATURE_NO_TITLE); // remove the interface title

GetWindow (). setFlags (WindowManager. LayoutParams. FLAG_FULLSCREEN,

WindowManager. LayoutParams. FLAG_FULLSCREEN );

// Reset the page size.

SetContentView (R. layout. main );

Init ();

}

 

Private void init (){

Start = (Button) this. findViewById (R. id. start );

Stop = (Button) this. findViewById (R. id. stop );

Start. setOnClickListener (new TestAudioListener ());

Stop. setOnClickListener (new TestAudioListener ());

CreatAudioRecord ();

}

 

Private void creatAudioRecord (){

// Obtain the buffer byte size

BufferSizeInBytes = AudioRecord. getMinBufferSize (sampleRateInHz,

ChannelConfig, audioFormat );

// Create an AudioRecord object

AudioRecord = new AudioRecord (audioSource, sampleRateInHz,

ChannelConfig, audioFormat, bufferSizeInBytes );

}

 

Class TestAudioListener implements OnClickListener {

 

@ Override

Public void onClick (View v ){

If (v = Start ){

StartRecord ();

}

If (v = Stop ){

StopRecord ();

}

 

}

 

}

 

Private void startRecord (){

AudioRecord. startRecording ();

// Set the recording status to true

IsRecord = true;

// Enable the audio file writing thread

New Thread (new AudioRecordThread (). start ();

}

 

Private void stopRecord (){

Close ();

}

 

Private void close (){

If (audioRecord! = Null ){

System. out. println ("stopRecord ");

IsRecord = false; // stop file writing

AudioRecord. stop ();

AudioRecord. release (); // release resources

AudioRecord = null;

}

}

 

Class AudioRecordThread implements Runnable {

@ Override

Public void run (){

WriteDateTOFile (); // write raw data to the file

CopyWaveFile (AudioName, NewAudioName); // Add the header file to the raw data

}

}

 

/**

* Data is written to a file but cannot be played, because the audio obtained by AudioRecord is the raw RAW Raw raw audio,

* If you want to play a video, you must add some format or encoding header information. But the advantage is that you can process the raw audio data. For example, you need to be a talking TOM.

* The Cat processes the audio here and re-encapsulates the audio. Therefore, the obtained audio is easier to process.

*/

Private void writeDateTOFile (){

// A new byte array is used to store some bytes of data. The size is the buffer size.

Byte [] audiodata = new byte [bufferSizeInBytes];

FileOutputStream fos = null;

Int readsize = 0;

Try {

File file = new File (AudioName );

If (file. exists ()){

File. delete ();

}

Fos = new FileOutputStream (file); // creates an object that can be accessed in bytes.

} Catch (Exception e ){

E. printStackTrace ();

}

While (isRecord = true ){

Readsize = audioRecord. read (audiodata, 0, bufferSizeInBytes );

If (AudioRecord. ERROR_INVALID_OPERATION! = Readsize ){

Try {

Fos. write (audiodata );

} Catch (IOException e ){

E. printStackTrace ();

}

}

}

Try {

Fos. close (); // close the write stream

} Catch (IOException e ){

E. printStackTrace ();

}

}

 

// Obtain the audio file that can be played.

Private void copyWaveFile (String inFilename, String outFilename ){

FileInputStream in = null;

FileOutputStream out = null;

Long totalAudioLen = 0;

Long totalDataLen = totalAudioLen + 36;

Long longSampleRate = sampleRateInHz;

Int channels = 2;

Long byteRate = 16 * sampleRateInHz * channels/8;

Byte [] data = new byte [bufferSizeInBytes];

Try {

In = new FileInputStream (inFilename );

Out = new FileOutputStream (outFilename );

TotalAudioLen = in. getChannel (). size ();

TotalDataLen = totalAudioLen + 36;

WriteWaveFileHeader (out, totalAudioLen, totalDataLen,

LongSampleRate, channels, byteRate );

While (in. read (data )! =-1 ){

Out. write (data );

}

In. close ();

Out. close ();

} Catch (FileNotFoundException e ){

E. printStackTrace ();

} Catch (IOException e ){

E. printStackTrace ();

}

}

 

/**

* A header is provided here. Insert this information to obtain the files that can be played.

* For the reason why I inserted these 44 bytes, this is really not in-depth research, but you just open a wav

* For audio files, you can find that the header file is basically the same. Files in each format have

* Your Own header file.

*/

Private void WriteWaveFileHeader (FileOutputStream out, long totalAudioLen,

Long totalDataLen, long longSampleRate, int channels, long byteRate)

Throws IOException {

Byte [] header = new byte [44];

Header [0] = 'R'; // RIFF/WAVE header

Header [1] = 'I ';

Header [2] = 'F ';

Header [3] = 'F ';

Header [4] = (byte) (totalDataLen & 0xff );

Header [5] = (byte) (totalDataLen> 8) & 0xff );

Header [6] = (byte) (totalDataLen> 16) & 0xff );

Header [7] = (byte) (totalDataLen> 24) & 0xff );

Header [8] = 'W ';

Header [9] = 'a ';

Header [10] = 'V ';

Header [11] = 'E ';

Header [12] = 'F'; // 'fmt' chunk

Header [13] = 'M ';

Header [14] = 'T ';

Header [15] = '';

Header [16] = 16; // 4 bytes: size of 'fmt' chunk

Header [17] = 0;

Header [18] = 0;

Header [19] = 0;

Header [20] = 1; // format = 1

Header [21] = 0;

Header [22] = (byte) channels;

Header [23] = 0;

Header [24] = (byte) (longSampleRate & 0xff );

Header [25] = (byte) (longSampleRate> 8) & 0xff );

Header [26] = (byte) (longSampleRate> 16) & 0xff );

Header [27] = (byte) (longSampleRate> 24) & 0xff );

Header [28] = (byte) (byteRate & 0xff );

Header [29] = (byte) (byteRate> 8) & 0xff );

Header [30] = (byte) (byteRate> 16) & 0xff );

Header [31] = (byte) (byteRate> 24) & 0xff );

Header [32] = (byte) (2*16/8); // block align

Header [33] = 0;

Header [34] = 16; // bits per sample

Header [35] = 0;

Header [36] = 'D ';

Header [37] = 'a ';

Header [38] = 'T ';

Header [39] = 'a ';

Header [40] = (byte) (totalAudioLen & 0xff );

Header [41] = (byte) (totalAudioLen> 8) & 0xff );

Header [42] = (byte) (totalAudioLen> 16) & 0xff );

Header [43] = (byte) (totalAudioLen> 24) & 0xff );

Out. write (header, 0, 44 );

}

 

@ Override

Protected void onDestroy (){

Close ();

Super. onDestroy ();

}

}

 

Android learning and sharing from zookeeper

Related Article

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.