SoFunction
Updated on 2025-04-10

Android implements accompaniment recording and synthesis of MP3

This article shares the specific code for Android to implement accompaniment recording and synthesis of MP3 for your reference. The specific content is as follows

The basic implementation ideas are as follows:

1. Use the audio recording class (AudioRecord) that comes with Android to realize recording.

 /**
   * Play accompaniment
   */
 private MediaPlayer player;
 /**
   * Return button
   */
 private ImageView btnBack;
 /**
   * Switch songs
   */
 private Button btnSwitchSong;
 /**
   * Backing time
   */
 private TextView tv_recod_time;
 /**
   * Lyrics VIEW
   */
 private LyricView lv_lyric;
 /**
   * Start recording
   */
 private Button btnPlay;
 /**
   * Title
   */
 private TextView ivTitle;
 private boolean canPlay = true;
 private boolean isPause = false;
 
 /***
   * Background music mode
   */
 private BackgroudMusicMode mode = ;
 /**
   * Song id
   */
 private String songId;
 /**
   * Song title
   */
 private String songName;
 /**
   * Singer's name
   */
 private String singerName;
 /**
   * Accompaniment file
   */
 private File file;
 /**
   * Is it recording?
   */
 private boolean isStart = false;
 /**
   * Recording status
   */
 private boolean starting = false;
 /**
   * Accompaniment time
   */
 private int bztimetmp = 0;
 /**
   * Accompaniment time
   */
 private String bztime = "";
 
 /**
   * Recording time
   */
 private int recordTimeLength=0;
 /**
   * Updated accompaniment time
   */
 private RecordTask rt = null;
 
 /**
   * Recording frequency, unit hz. Please note the value here. If you write it poorly, you may have an error when instantiating the AudioRecord object.  I started writing it as 11025 and it won't work.  It depends on the hardware device
   * Set audio sampling rate, 44100 is the current standard, but some devices still support 22050, 16000, 11025
   */
 private int sampleRateInHz = 44100;
 /**
   * Set the audio recording channel CHANNEL_IN_STEREO as dual channel and CHANNEL_CONFIGURATION_MONO as mono channel
   */
 private int channelConfig = AudioFormat.CHANNEL_CONFIGURATION_MONO;
 
 /**
   * Audio data format: PCM 16 bits per sample.  Ensure equipment support.  PCM 8 bits per sample.  It may not be supported by the device.
   */
 private int audioFormat = AudioFormat.ENCODING_PCM_16BIT;
 
 /**
   * Adjust playback volume
   */
 private AudioManager audioManager;
 
 /**
   * Maximum volume
   */
 private int maxVolume = 0;
 
 /**
   * Current volume
   */
 private int currentVolume = 0;
 
 /**
   * AudioRecord write buffer size
   */
 protected int m_in_buf_size;
 /**
   * Record audio objects
   */
 private AudioRecord mRecorder;
 /**
   * Entered byte array
   */
 private byte[] m_in_bytes;
 /**
   * Storing the size of the entered byte array
   */
 private LinkedList<byte[]> m_in_q;
 /**
   * AudioTrack playback buffer size
   */
 private int m_out_buf_size;
 /**
   * Play audio objects
   */
 private AudioTrack mAudioTrack;
 /**
   * Played byte array
   */
 private byte[] m_out_bytes;
 /**
   * Record audio thread
   */
 private Thread record;
 /**
   * Play audio thread
   */
 private Thread play;
 /**
   * Flag to stop thread
   */
 private boolean flag = true;
 /**
   * Whether to start echo
   */
 private boolean room_flag = true;
 
 /***There is a component that plays lyrics
   /***
   * Initialization
   */
 private void init() {
  
  audioManager = (AudioManager)getSystemService(Context.AUDIO_SERVICE);
  maxVolume = (AudioManager.STREAM_VOICE_CALL);
  currentVolume = (AudioManager.STREAM_VOICE_CALL);
  registerHeadsetPlugReceiver();
  ycApplication = (YueChangApplication) getApplication();
  coverDao = new CoverDao(getApplicationContext());
  Bundle bundle = getIntent().getExtras();
  songId = ("songId");
  songName = ("songName");
  singerName = ("singerName");
  if (songId != null) {
   // AudioRecord gets the size of the minimum buffer to record   m_in_buf_size = (sampleRateInHz, channelConfig, audioFormat);
   // Instantiate the playback audio object   mRecorder = new AudioRecord(, sampleRateInHz, channelConfig, audioFormat,
     m_in_buf_size);
   // Instantiate a byte array with the length of the minimum buffer   m_in_bytes = new byte[m_in_buf_size];
   // Instantiate a linked list to store the number of byte groups   m_in_q = new LinkedList<byte[]>();
 
   // AudioTrack gets the size of the minimum playback buffer   m_out_buf_size = (sampleRateInHz, channelConfig, audioFormat);
   // Instantiate the playback audio object   mAudioTrack = new AudioTrack(AudioManager.STREAM_MUSIC, sampleRateInHz, channelConfig, audioFormat,
     m_out_buf_size, AudioTrack.MODE_STREAM);
   // Instantiate a byte array with a length of playback minimum buffer size   m_out_bytes = new byte[m_out_buf_size];
   record = new Thread(new recordSound());
   
//   if(()){
    
//   }else{
//    m_out_trk = new AudioTrack(AudioManager.STREAM_MUSIC, sampleRateInHz, channelConfig, audioFormat,
//      m_out_buf_size, AudioTrack.MODE_STREAM);
//   }
   
 
  }
 }
 
  /**
   *
   * Class Description: Recording Thread
   *
   * @version 1.0
   */
 class recordSound implements Runnable {
  @Override
  public void run() {
   // Initialize the output stream   DataOutputStream dos = null;
   try {
    File audioFile = new File((songId));
    // Initialize the output stream    dos = new DataOutputStream(new BufferedOutputStream(new FileOutputStream(audioFile)));
    byte[] bytes_pkg;
    if (() == AudioRecord.STATE_UNINITIALIZED) {
     // Instantiate the playback audio object     mRecorder = new AudioRecord(, sampleRateInHz, channelConfig,
       audioFormat, m_in_buf_size);
    }
 
    // Start recording    ();
    while (flag) {
     int size = (m_in_bytes, 0, m_in_buf_size);
     bytes_pkg = m_in_bytes.clone();
     if (m_in_q.size() >= 2) {
      m_in_q.removeFirst();
     }
     m_in_q.add(bytes_pkg);
     if ((() && ())
       || (!() && ())) {
      //(().getName(), "Start recording playback 1");      if (play == null||!room_flag) {
       //(().getName(), "Start recording playback 2");       room_flag = true;
       play = new Thread(new playRecord());
       // Start the playback thread       ();
      }
 
     } else {
      if(room_flag||play != null){
       //(().getName(), "Close recording playback 1");       room_flag = false;
       if (play != null) {
        ();
       }
       play = null;
      }
     }
     // Write to PCM file     (bytes_pkg, 0, size);
     ();
    }
 
   } catch (Exception e) {
    // TODO: handle exception
    ();
   } finally {
    try {
     // Turn off recording     if (mRecorder != null) {
      try {
       if (() == AudioRecord.STATE_INITIALIZED) {
        // Turn off recording        ();
        ();
       }
      } catch (Exception e2) {
       // TODO: handle exception
      }
     }
     if (dos != null) {
      ();
     }
    } catch (Exception e2) {
     // TODO: handle exception
     ();
    }
   }
 
  }
 }

2. After recording is completed, call the open source tool (Mad) to realize PCM synthesis and output to MP3 file.

The main synthesis method is called:

/***
  * Method description: Local method calls JNI to merge mp3PCM and sourcePCM
  * @param sourcePCM
  * @param mp3PCM
  * @param mixPCM
  * @return
  */
 public static native int mix2PCMToPCM(String sourcePCM, String mp3PCM, String mixPCM);
 
 String recordPCMPath = (songId); //The PCM file generated by recording      String accompanyPCMPath = (songId); //The PCM file generated by accompaniment decoding      String mixPCMPath = (songId); //The synthetic PCM file      String mixMP3Path = SongUtil.getMixSingMp3Path(songId); //The synthetic MP3 file      // Mix      int code = SongEncodeUtil.mix2PCMToPCM(recordPCMPath, accompanyPCMPath, mixPCMPath);
      if (code == 0) {
       // Convert the mixed audio format TO mp3       int i = (mixPCMPath, mixMP3Path, m_in_buf_size);
       (().getName(), "Convert" + i + "Mixing Completed");
       saveMp3File(mixMP3Path);
      }

The above is all the content of this article. I hope it will be helpful to everyone's study and I hope everyone will support me more.