Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

What is the method of Android audio development to record audio?

2025-03-28 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/02 Report--

This article mainly explains "what is the method of Android audio development and recording audio". The content of the article is simple and clear, and it is easy to learn and understand. Please follow the editor's train of thought to study and learn "what is the method of Android audio development and recording audio".

First of all, take a look at the audio recording and playback effect diagram:

Above is the recording: long press to record, support sound wave animation, right slide delete and so on. Audio recording in pcm, wav and mp3 formats is supported.

The following is playback: click icon on the left speaker to start playing the newly recorded local audio file [also supports online audio playback], support playback progress, support switching playback mode (handset / speaker / headset), etc.

1. Audio recording permissions:

No matter before you develop any function, you have to add and apply for relevant permissions before the follow-up work can be carried out normally. The permissions required for audio recording are as follows, and you need to apply for these sensitive permissions dynamically in the code before you can record them normally:

Second, the configuration of recording files:

Through the first section talking about the basic concept of audio, we can know that the relevant configuration of recording should be carried out before recording, which directly determines the audio quality, file size, audio format and so on.

/ * related configuration of recording audio * / private void initConfig () {recordConfig = new RecordConfig (); / / sampling bit width recordConfig.setEncodingConfig (AudioFormat.ENCODING_PCM_16BIT); / / recording format recordConfig.setFormat (RecordConfig.RecordFormat.MP3); / / recordConfig.setFormat (RecordConfig.RecordFormat.WAV); / / sampling frequency recordConfig.setSampleRate (16000) String recordDir = String.format (Locale.getDefault (), "% s/Record/zhongyao/", Environment.getExternalStorageDirectory (). GetAbsolutePath ()); / / Storage directory recordConfig.setRecordDir (recordDir); AudioRecordManager.getInstance (). SetCurrentConfig (recordConfig);} III. Audio recording:

There are mainly two wrapper classes for audio recording: AudioRecorder and AudioRecordManager.

AudioRecorder: mainly use the AudioRecord of the system for recording. And the recorded audio files are merged and transcoded to generate the audio files we need. This file is a global singleton, ensuring that there is only one instance of the audio recording class.

AudioRecordManager: the encapsulation management of AudioRecorder, through which the interaction with the outside world is completed, including various lifecycle control calls for recording, etc. It reduces the direct interaction between the outside world and AudioRecorder, and has achieved better management of the recording class, which is also a global singleton class.

1. Initialize the recording object:

Here, bufferSizeInBytes [buffer byte size] and audioRecord objects are generated according to the previous recording configuration.

/ * create default recording object * / public void prepareRecord () {/ / get buffer byte size if (bufferSizeInBytes = = 0) {bufferSizeInBytes = AudioRecord.getMinBufferSize (currentConfig.getSampleRate (), currentConfig.getChannelConfig (), currentConfig.getEncodingConfig () } if (audioRecord = = null) {audioRecord = new AudioRecord (AUDIO_INPUT, currentConfig.getSampleRate (), currentConfig.getChannelConfig (), currentConfig.getEncodingConfig (), bufferSizeInBytes);} audioRecordStatus = AudioRecordStatus.AUDIO_RECORD_PREPARE;} 2, record wav audio file:

Wav audio files are lossless, so the sound quality is close to the native, but it is precisely because it is lossless that wav audio files are hardly compressed and will be relatively large.

To record wav audio, we must first record it, get the pcm file, then merge the pcm file, and then convert it into wav audio file.

(1) start recording pcm files:

Private void startPcmRecorder () {audioRecordStatus = AudioRecordStatus.AUDIO_RECORD_START; notifyState (); Logger.d (TAG, "start recording Pcm"); FileOutputStream fos = null; try {fos = new FileOutputStream (tmpFile); audioRecord.startRecording (); byte [] byteBuffer = new byte [bufferSizeInBytes] While (audioRecordStatus = = AudioRecordStatus.AUDIO_RECORD_START) {int end = audioRecord.read (byteBuffer, 0, byteBuffer.length); notifyData (byteBuffer); fos.write (byteBuffer, 0, end); fos.flush ();} audioRecord.stop (); files.add (tmpFile) If (audioRecordStatus = = AudioRecordStatus.AUDIO_RECORD_STOP) {makeFile ();} else {Logger.d (TAG, "cancel recording...");}} catch (Exception e) {Logger.e (e, TAG, e.getMessage ()); notifyError ("recording failed") } finally {try {if (fos! = null) {fos.close ();}} catch (IOException e) {e.printStackTrace ();}} if (audioRecordStatus! = AudioRecordStatus.AUDIO_RECORD_PAUSE) {audioRecordStatus = AudioRecordStatus.AUDIO_RECORD_IDLE NotifyState (); Logger.d (TAG, "recording ends");}}

(2) merge multiple pcm files:

/ * merge pcm files * / private void mergePcmFile () {boolean mergeSuccess = mergePcmFiles (resultFile, files); if (! mergeSuccess) {notifyError ("merge failed");}}

(3) convert the merged pcm file into wav file:

/ * add Wav header file * / private void makeWav () {if (! FileUtil.isFile (resultFile) | | resultFile.length () = = 0) {return;} byte [] header = WavUtils.generateWavFileHeader ((int) resultFile.length (), currentConfig.getSampleRate (), currentConfig.getChannelCount (), currentConfig.getEncoding ()); WavUtils.writeHeader (resultFile, header);} 3. Record MP3 audio file

Compared with WAV audio files, MP3 audio files are more common and are used more commercially, because MP3 audio is compressed and the file size is only 1/12 of WAV, but there is almost no big difference in sound quality. When there is no extremely high requirement for sound quality, such as recording files, MP3 format is an excellent choice.

(1) start recording audio cache:

Here there is a thread Mp3EncodeThread that continuously encodes and decodes the byte array byteBuffer generated by the recording into a MP3 file.

Private void startMp3Recorder () {audioRecordStatus = AudioRecordStatus.AUDIO_RECORD_START; notifyState (); try {audioRecord.startRecording (); short [] byteBuffer = new short [bufferSizeInBytes]; while (audioRecordStatus = = AudioRecordStatus.AUDIO_RECORD_START) {int end = audioRecord.read (byteBuffer, 0, byteBuffer.length) If (mp3EncodeThread! = null) {mp3EncodeThread.addChangeBuffer (new Mp3EncodeThread.ChangeBuffer (byteBuffer, end));} notifyData (ByteUtils.toBytes (byteBuffer));} audioRecord.stop ();} catch (Exception e) {Logger.e (e, TAG, e.getMessage ()) NotifyError ("recording failed");} if (audioRecordStatus! = AudioRecordStatus.AUDIO_RECORD_PAUSE) {if (audioRecordStatus = = AudioRecordStatus.AUDIO_RECORD_CANCEL) {deleteMp3Encoded ();} else {stopMp3Encoded ();}} else {Logger.d (TAG, "pause") }}

(2) MP3 audio codec:

Android native audio recording supports the direct generation of WAV files, but in fact, it does not support the direct generation of MP3 files. Here corresponds to MP3 codec, mainly uses the open source libmp3lame.so audio codec library. The following are lame codec methods and Mp3Encoder classes:

MP3 encoding and decoding method:

Private void lameData (ChangeBuffer changeBuffer) {if (changeBuffer = = null) {return;} short [] buffer = changeBuffer.getData (); int readSize = changeBuffer.getReadSize (); if (readSize > 0) {int encodedSize = Mp3Encoder.encode (buffer, buffer, readSize, mp3Buffer); if (encodedSize

< 0) { Logger.e(TAG, "Lame encoded size: " + encodedSize); } try { os.write(mp3Buffer, 0, encodedSize); } catch (IOException e) { Logger.e(e, TAG, "Unable to write to file"); } } } Mp3Encoder类: public class Mp3Encoder { static { System.loadLibrary("mp3lame"); } public native static void close(); public native static int encode(short[] buffer_l, short[] buffer_r, int samples, byte[] mp3buf); public native static int flush(byte[] mp3buf); public native static void init(int inSampleRate, int outChannel, int outSampleRate, int outBitrate, int quality); public static void init(int inSampleRate, int outChannel, int outSampleRate, int outBitrate) { init(inSampleRate, outChannel, outSampleRate, outBitrate, 7); }} (3)生成libmp3lame.so: 本项目提供的源码中有lame的jni源码,如果想生成libmp3lame.so文件,供自己的项目使用,那么需要对Mp3Encoder.c 和Mp3Encoder.h文件进行修改,然后通过ndk build 生成该so文件。 修改的内容主要是把文件中的Mp3Encoder路径改成自己项目中的Mp3Encoder的路径,否则会找不到相关的native方法。 另外一般情况下,cpu类型支持 armeabi-v7a 、arm64-v8a 两种即可,如果想支持其他的可在Application.mk中添加。

After the above file has been modified, the corresponding libmp3lame.so file can be compiled and generated through the ndk-build instruction.

Place the files of different CPU types of so under jniLibs, or under the path configured by sourceSets, such as:

SourceSets.main {jni.srcDirs = [] / disable automatic ndk-build call jniLibs.srcDirs = ['libs']}

It can be recorded in MP3 audio format.

4. Audio recording management [AudioRecordManager]:

Through the AudioRecorderManager of the global singleton mode to interact with the business, it can not only ensure the singleness of the audio recording instance, but also better manage the audio life cycle.

/ * Create by zhongyao on 2021-8-18 * Description: audio recording management class * / public class AudioRecordManager {private static final String TAG = "AudioRecordManager"; private AudioRecordManager () {} public static AudioRecordManager getInstance () {return AudioRecordManagerHolder.instance;} public static class AudioRecordManagerHolder {public static AudioRecordManager instance = new AudioRecordManager ();} public void setCurrentConfig (RecordConfig recordConfig) {AudioRecorder.getInstance () .setCurrentConfig (recordConfig) } public RecordConfig getCurrentConfig () {return AudioRecorder.getInstance () .getCurrentConfig ();} / * recording status monitoring callback * / public void setRecordStateListener (RecordStateListener listener) {AudioRecorder.getInstance () .setRecordStateListener (listener) } / * recording data monitoring callback * / public void setRecordDataListener (RecordDataListener listener) {AudioRecorder.getInstance () .setRecordDataListener (listener);} / * recording visualization data callback, Fourier converted frequency domain data * / public void setRecordFftDataListener (RecordFftDataListener recordFftDataListener) {AudioRecorder.getInstance () .setRecordFftDataListener (recordFftDataListener) * / public void setRecordResultListener (RecordResultListener listener) {AudioRecorder.getInstance () .setRecordResultListener (listener);} / * recording volume monitoring callback * / public void setRecordSoundSizeListener (RecordSoundSizeListener listener) {AudioRecorder.getInstance () .callback (listener) } public void setStatus (AudioRecordStatus curAudioRecordStatus) {switch (curAudioRecordStatus) {case AUDIO_RECORD_IDLE: break; case AUDIO_RECORD_PREPARE: AudioRecorder.getInstance () .prepareRecord (); break; case AUDIO_RECORD_START: AudioRecorder.getInstance () .startRecord (); break Case AUDIO_RECORD_PAUSE: AudioRecorder.getInstance (). PauseRecord (); break; case AUDIO_RECORD_STOP: AudioRecorder.getInstance (). StopRecord (); break; case AUDIO_RECORD_CANCEL: AudioRecorder.getInstance (). CancelRecord (); break Case AUDIO_RECORD_RELEASE: AudioRecorder.getInstance () .releaseRecord (); break; default: break;}} public AudioRecordStatus getStatus () {return AudioRecorder.getInstance () .getAudioRecordStatus ();} public String getAudioPath () {return AudioRecorder.getInstance () .getAudioPath () }} Thank you for your reading, the above is the content of "what is the method of Android audio development and recording audio". After the study of this article, I believe you have a deeper understanding of what is the method of Android audio development and recording audio, and the specific use needs to be verified in practice. Here is, the editor will push for you more related knowledge points of the article, welcome to follow!

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report