Android Audio Introduction

Common audio codec types :AAC, OPUS, MP3, AMR, Ogg, PCM

AAC: advanced audio encoding corresponding to.m4a(audio/ M4A) or.3pg(audio/ 3GPP) files HEAAC: advanced AAC, used more.

OPUS: Lossy voice encoding format, recently developed by the Internet Engineering Task Force (IETF), for real-time voice transmission over the network, such as voice calls

MP3: The most widely used audio codec corresponds to.mp3(audio/ MP3), which is commonly used by various music sites.

AMR: Adaptive multirate audio codec, commonly used for voice calling programs.

Ogg: Developed patentless audio codecs whose quality is comparable to that of commercial and hand-patented MP3 and AAC codecs.

PCM: Raw audio, directly hired by audio Record on the Android platform, uncoded.

AAC or OPUS is generally used in live video and voice calls. If the voice needs to be processed, PCM original audio processing is required, and then coding is carried out.

####Android Audio capture (capture)

There are three kinds of audio collection on Android platform: 1. Use android built-in application 2. Use MediaRecorder to capture audio 3. Use AudioRecord to capture audio. As the flexibility of these three approaches increases, so does the amount of work required.

First, Android built-in apps.

Intent intent=new Intent(MediaStore.Audio.Media.RECORD_SOUND_ACTION); startActivityForResult(intent,0); // startActivityForResult is the least flexible way to get the result of an audio recording.

Two, the use of MediaRecorder audio capture.

This scheme is much more flexible than calling the system built-in procedures, which is convenient for developers to layout on the UI interface. Moreover, the system is well packaged and easy to use. The only disadvantage is that the audio recorded by using it is coded, and there is no way to get the original audio. At the same time MediaRecorder can be used for audio capture can also be used for video capture quite powerful. There is no special need in the actual development of words, with more!

Use steps:

Create MediaRecorder object, call the following method (Ps: call order is very important to the result. MediaRecorder recorder=new MediaRecorder(); / / create MediaRecoder object 1. Recorder. SetAudioSource (MediaRecorder. AudioSource. MIC); / / call setAudioSource method (called the first method) the MediaRecorder. AudioSource. CAMCORDER and MediaRecorder AudioSource. VOICE_RECOGNITION when the equipment is. >=2 microphones can use them. The MediaRecorder. AudioSource. VOICE_CALL audio from the phone 2. Recorder. SetOutputFormat (MediaRecorder. OutputFormat. THREE_GPP); / / setOutputFormat method. The second method (call) the MediaRecorder OutputFormat. THREE_GPP output files will be an extension of the file (. 3 gp). It may contain audio and video. MediaRecorder. OutputFormat. A MPEG_4 MPEG_4 output file, it may contain audio and video. 3. recorder.setAudioEncoder(MediaRecorder.AudioEncoder.AAC); //setAudioEncoder method (this is the third method called) 4. Recorder. SetOutputFile (URL); //setOutputFile method URL is the target file path (this is the fourth method to be called). Once the above four methods have been called, you can control recording and pause recording like MediaPlayer.Copy the code


<? The XML version = "1.0" encoding = "utf-8"? > <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:orientation="vertical" android:layout_width="fill_parent" android:layout_height="fill_parent" android:background="#fff" Android :gravity="center"> <Button id:id="@+id/StartRecording" Android :layout_width="wrap_content" Android: Layout_height ="wrap_content"/> <Button Android :text=" Button" android:id="@+id/StopRecording" android:layout_width="wrap_content" android:layout_height="wrap_content"/> </LinearLayout>Copy the code
public class MainActivity extends Activity implements OnClickListener{ Button startRecording, stopRecording; // Start recording, stop recording, release resources MediaRecorder recorder; File audioFile; // Record saved file Boolean isRecoding=false; @override public void onCreate(Bundle savedInstanceState) {super.oncreate (savedInstanceState); requestWindowFeature(Window.FEATURE_NO_TITLE); setContentView(R.layout.main); init(); initListener(); } // initialize public void recording (){stopRecording = (Button) this.findViewById(r.id.toprecording); startRecording = (Button) this.findViewById(R.id.StartRecording); recorder = new MediaRecorder(); recorder.setAudioSource(MediaRecorder.AudioSource.MIC); / / set the source The microphone recorder. SetOutputFormat (MediaRecorder. OutputFormat. THREE_GPP); / / set the input format 3 gp recorder. SetAudioEncoder (MediaRecorder. AudioEncoder. The AMR_NB); / / set encoding AMR} / / set the listener public void initListener () {startRecording. SetOnClickListener (this); stopRecording.setOnClickListener(this); } public void recod(){// Check whether there is a memory card in the phone // Save the File path = new in the MediaRecorderTest folder under the SD card File(Environment.getExternalStorageDirectory().getAbsolutePath()+ "/MediaRecorderTest"); if(! path.exists()) { path.mkdirs(); } try { audioFile=new File(path,"test.3gp"); if(audioFile.exists()) { audioFile.delete(); } audioFile.createNewFile(); } catch (Exception e) {throw new RuntimeException("Couldn't create recording audio file", e); } recorder.setOutputFile(audioFile.getAbsolutePath()); // Set output file try {local.prepare (); } catch (IllegalStateException e) { throw new RuntimeException("IllegalStateException on MediaRecorder.prepare", e); } catch (IOException e) { throw new RuntimeException("IOException on MediaRecorder.prepare", e); } isRecoding=true; recorder.start(); } public void onClick(View v) {switch (v.getid ()) {// start recording case r.i.starrecording: Toast.maketext (mainactivity.this," start recording ", toast.length_short).show(); recod(); break; } // Stop recording case R.I.D. topRecording: {if(isRecoding) {toast.maketext (mainactivity.this," stop recording ", toast.length_short).show(); recorder.stop(); recorder.release(); } break; } default: break; }}}Copy the code
Other API methods for MediaRecoder: // Set the maximum allowed recording time in milliseconds. Must be used after setOutFormat and before prepare. SetMaxDuration (int); // Set the maximum number of bytes for recording files. Must be used after setOutFormat and before prepare. SetMaxFileSize (long) // The number of audio channels allowed to record, usually one channel (mono, 2 channels dual, stereo). It must be called before the prepare method is called. SetAudioChannels (int) // Allows you to specify the sampling rate for capturing and encoding audio. The hardware and the encoder used will determine the appropriate sampling rate. It must be called before the prepare method is called. SetAudioSamplingRate (int) // allows the number of bits per second (bits/s) used by the encoder when the audio is compressed. It must be called before the prepare method is called. SetAudioEncodingBitRate in (int)Copy the code
Three, use AudioRecord for audio capture.

This method is the most flexible of the three, allowing developers to maximize the amount of captured audio while capturing it in raw audio PCM format! You have to use it to collect audio for things like sound processing. In practical development, it is also the most common means to capture audio. It is also the focus of this article.

1. Specify the audio source This and the MediaRecorder is the same int audioSource = MediaRecorder. AudioSource. MIC. 2. Specify the sampling rate (MediaRecoder is usually 8000Hz, CD is usually 44100Hz) different Android phone hardware will be able to sample at different sampling rates. Where 11025 is a common sampling rate) int sampleRateInHz=11025; 3. Specify the number of channels for capturing audio. Specify the constant int channelConfig= Audioformat.channel_configuration_mono for this in the AudioFormat class; 4. Specify the audio quantization number. The following possible constants are specified in the AudioFormaat class. Usually we choose ENCODING_PCM_16BIT and ENCODING_PCM_8BIT and PCM stands for pulse code modulation, which is actually the original audio sample. // Therefore, you can set the resolution of each sample to 16 or 8 bits. 16 bits takes up more space and processing power, and the audio is more realistic. int audioFormat=AudioFormat.ENCODING_PCM_16BIT; Specifies the buffer size. You can get this by calling the getMinBufferSize method of the AudioRecord class. // Create AudioRecord. The AudioRecord class does not actually save the captured audio, so you need to manually create the file and save the download. AudioRecord record = new AudioRecord (audioSource sampleRateInHz, channelConfig, audioFormat, bufferSizeInBytes);Copy the code

The layout XML file is the same as in the MediaRecorder Demo, only 2 buttons! I will not post, the following post AudioRecord Demo source code.

public class MainActivity extends Activity implements OnClickListener { Button startRecordingButton, stopRecordingButton; // start recording, stop recordingFile recordingFile; Boolean isRecording = false; //true: recording AudioRecord AudioRecord =null; File parent=null; // File directory int bufferSize=0; // minimum buffer size int sampleRateInHz = 11025; Int channelConfig = Audioformat. CHANNEL_CONFIGURATION_MONO; // mono int audioFormat = audioformat.encoding_pcm_16bit; String TAG="AudioRecord"; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); requestWindowFeature(Window.FEATURE_NO_TITLE); setContentView(R.layout.main); init(); initListener(); } / / initializes the public void init () {startRecordingButton = (Button) the findViewById (R.i d.S tartRecordingButton); stopRecordingButton = (Button)findViewById(R.id.StopRecordingButton); bufferSize = AudioRecord.getMinBufferSize(sampleRateInHz,channelConfig, audioFormat); / / calculate the minimum buffer audioRecord = new audioRecord (MediaRecorder. AudioSource. MIC, sampleRateInHz channelConfig, audioFormat, bufferSize); / / create AudioRecorder object parent = new File (Environment. External.getexternalstoragedirectory () getAbsolutePath () + "/ AudiioRecordTest");  if(! parent.exists()) parent.mkdirs(); Create the folder / /} / / initializes the listener public void initListener () {startRecordingButton. SetOnClickListener (this); stopRecordingButton.setOnClickListener(this); {} public void onClick (View v) switch (v.g etId ()) {/ / recording case R.i d.S tartRecordingButton: {record (); break; } / / stop the recording case R.i d.S topRecordingButton: {stopRecording (); break; Public void record() {isRecording = true; new Thread(new Runnable() { @Override public void run() { isRecording = true; recordingFile = new File(parent,"audiotest.pcm"); if(recordingFile.exists()){ recordingFile.delete(); } try { recordingFile.createNewFile(); } catch (IOException e) { e.printStackTrace(); Log.e(TAG," error creating saved audio file "); } try { DataOutputStream dos = new DataOutputStream(new BufferedOutputStream(new FileOutputStream(recordingFile))); byte[] buffer = new byte[bufferSize]; audioRecord.startRecording(); // start recording int r = 0; while (isRecording) { int bufferReadResult = audioRecord.read(buffer,0,bufferSize); for (int i = 0; i < bufferReadResult; i++) { dos.write(buffer[i]); } r++; } audioRecord.stop(); // Stop recording dos.close(); } catch (Throwable t) { Log.e(TAG, "Recording Failed"); } } }).start(); } public void stopRecording() {isRecording = false; }}Copy the code

Note that the following permissions are added to each Demo:

<uses-permission android:name="android.permission.RECORD_AUDIO"/>
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
Copy the code
4. Note

MediaRecorder audio collection Demo source code

AudioRecord collection audio Demo source code

Raw audio PCM player: Use method: file -> import -> naked data and then fill in the corresponding parameters according to your recording configuration can play!

Check out the latest CodeEngine articles.