Audio recording is a popular feature in many Android applications, enabling users to capture sound easily. This guide will teach you how to implement audio recording in your Android app using the MediaRecorder class.
Here is a basic example of how to record audio in an Android application:
// Request necessary permissions in AndroidManifest.xml
// Activity code
public class MainActivity extends AppCompatActivity {
private MediaRecorder mediaRecorder;
private String fileName;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
fileName = getExternalFilesDir(Environment.DIRECTORY_MUSIC).getAbsolutePath() + "/audiorecordtest.3gp";
mediaRecorder = new MediaRecorder();
}
private void startRecording() {
mediaRecorder.setAudioSource(MediaRecorder.AudioSource.MIC);
mediaRecorder.setOutputFormat(MediaRecorder.OutputFormat.THREE_GPP);
mediaRecorder.setAudioEncoder(MediaRecorder.AudioEncoder.AMR_NB);
mediaRecorder.setOutputFile(fileName);
try {
mediaRecorder.prepare();
mediaRecorder.start();
} catch (IOException e) {
e.printStackTrace();
}
}
private void stopRecording() {
mediaRecorder.stop();
mediaRecorder.release();
mediaRecorder = null;
}
}
Make sure to handle runtime permissions for Android 6.0 (API level 23) and higher. You can check for permissions and request them as needed to ensure your app works smoothly on all devices.
How do I avoid rehashing overhead with std::set in multithreaded code?
How do I find elements with custom comparators with std::set for embedded targets?
How do I erase elements while iterating with std::set for embedded targets?
How do I provide stable iteration order with std::unordered_map for large datasets?
How do I reserve capacity ahead of time with std::unordered_map for large datasets?
How do I erase elements while iterating with std::unordered_map in multithreaded code?
How do I provide stable iteration order with std::map for embedded targets?
How do I provide stable iteration order with std::map in multithreaded code?
How do I avoid rehashing overhead with std::map in performance-sensitive code?
How do I merge two containers efficiently with std::map for embedded targets?