Posted on

Android Record Audio


Android Record Audio

Hey guys, I’ve been thinking about making a calling app for a long time and now is the time to start making it! It has a few steps: record audio, send, receive, play it. Today we’re going to build first one. And I think you cannot really call yourself a mobile developer if you don’t know how to implement the key features on mobile – audio/video calls. That’s really cool stuff, if you’re exited, then let’s get started!

 

Record

MediaRecorder API is pretty simple to use. We’ll record audio and save it on internal storage. To be able to record audio we need RECORD_AUDIO permission. It has dangerous level protection, which means stating from Marshmallow user grants it during run time. I used Easy Permissions library which has those handy AfterPermissionGranted annotations which save you from writing any code in onRequestPermissionResult.

Once granted, let’s create a MediaRecorder instance and give it output file.

Once done, call

Play

For playing we use MediaPlayer class

to stop

The core methods are native implementation in C++ which you can check here.

Customize visuals

How about making a visual display of the playing track? Progress bar with ProgressBar.Horizontal style and indeterminate set to false makes the work. There’s just two methods of it we’ll use – setMax() and setProgress(). First one sets the duration. Let’s say we recorded an audio of 5000 ms, that will be the max value and we update progress every millisecond.

Now where do we get played part update listener? Do we get it from MediaPlayer? Fortunately there’s no need for it to call any methods every millisecond. We just can you ValueAnimator over int starting with 0, end of track duration in milliseconds andset animation duration to track duration, which will make onAnimationUpdate being called every ms. Perfect for us, we just set bar progress to the value of animator instance. There’s cancel/pause methods on it. So we can stop value animator which updates progress bar, when, for example, there’s an error of MediaPlayer. Super easy by setting onErrorListener on MediaPlayer.

That’s what I got so far

Android Record Audio

code is pretty simple

Display Play Time

Android Record Audio

Pretty simple to implement that. I have this milliseconds to time formatter method

We just use it for duration of the track and each time on value animator update.

 

Ok, that’s a first part of Audio calling app. Stay tuned for more! You can check GitHub repo here