AudioRecord object not initializing
The trick with using AudioRecord is that each device may have different initialization settings, so you will have to create a method that loops over all possible combinations of bit rates, encoding, etc.
private static int[] mSampleRates = new int[] { 8000, 11025, 22050, 44100 };
public AudioRecord findAudioRecord() {
for (int rate : mSampleRates) {
for (short audioFormat : new short[] { AudioFormat.ENCODING_PCM_8BIT, AudioFormat.ENCODING_PCM_16BIT }) {
for (short channelConfig : new short[] { AudioFormat.CHANNEL_IN_MONO, AudioFormat.CHANNEL_IN_STEREO }) {
try {
Log.d(C.TAG, "Attempting rate " + rate + "Hz, bits: " + audioFormat + ", channel: "
+ channelConfig);
int bufferSize = AudioRecord.getMinBufferSize(rate, channelConfig, audioFormat);
if (bufferSize != AudioRecord.ERROR_BAD_VALUE) {
// check if we can instantiate and have a success
AudioRecord recorder = new AudioRecord(AudioSource.DEFAULT, rate, channelConfig, audioFormat, bufferSize);
if (recorder.getState() == AudioRecord.STATE_INITIALIZED)
return recorder;
}
} catch (Exception e) {
Log.e(C.TAG, rate + "Exception, keep trying.",e);
}
}
}
}
return null;
}
AudioRecord recorder = findAudioRecord();
recorder.release();
Android AudioRecord won't initialize
I found the answer myself. It had to do with permissions.
The problem was that I am running API version 23 (Android 6.0.1) on my phone, which no longer uses only the manifest file to handle permissions. From version 23, permissions are granted in run-time instead. I added a method that makes sure to request the permission in run-time, and when I had allowed it once on my phone, it worked.
private void requestRecordAudioPermission() {
//check API version, do nothing if API version < 23!
int currentapiVersion = android.os.Build.VERSION.SDK_INT;
if (currentapiVersion > android.os.Build.VERSION_CODES.LOLLIPOP){
if (ContextCompat.checkSelfPermission(this, Manifest.permission.RECORD_AUDIO) != PackageManager.PERMISSION_GRANTED) {
// Should we show an explanation?
if (ActivityCompat.shouldShowRequestPermissionRationale(this, Manifest.permission.RECORD_AUDIO)) {
// Show an expanation to the user *asynchronously* -- don't block
// this thread waiting for the user's response! After the user
// sees the explanation, try again to request the permission.
} else {
// No explanation needed, we can request the permission.
ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.RECORD_AUDIO}, 1);
}
}
}
}
@Override
public void onRequestPermissionsResult(int requestCode, String permissions[], int[] grantResults) {
switch (requestCode) {
case 1: {
// If request is cancelled, the result arrays are empty.
if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
// permission was granted, yay! Do the
// contacts-related task you need to do.
Log.d("Activity", "Granted!");
} else {
// permission denied, boo! Disable the
// functionality that depends on this permission.
Log.d("Activity", "Denied!");
finish();
}
return;
}
// other 'case' lines to check for other
// permissions this app might request
}
}
I then call requestRecordAudioPermission() from the onCreate() method in my main activity before creating the AudioRecord.
AudioRecord object not initializing in a project
Got the solution:
Recently I updated my phone to Marshmallow. In Marshmallow there is a new permission system. I switched on these permissions as bellow the recording works just fine.
Android AudioRecord fails to initialise(Other solutions not working)
Step 1) Check your manifest to ensure add RECORD_AUDIO permission under application section. e.g.
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.colibri.audioloopback">
<application
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:supportsRtl="true"
android:theme="@style/AppTheme">
<activity android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
<uses-permission android:name="android.permission.RECORD_AUDIO" />
</manifest>
Step 2) If your device is M or later, you need to grant the permssion from Settings->App->Your App->Permissions.
Step 3) Refer to below code snippet if still doesn't work.
public void audioRecordLoop() throws Exception {
Log.e(TAG,"start audioRecordLoop");
int channelConfig = mChannels == 2?
AudioFormat.CHANNEL_IN_STEREO:
AudioFormat.CHANNEL_IN_MONO;
int bufferSize = AudioRecord.getMinBufferSize(
mSampleRateHz, channelConfig, mAudioEncoding);
mAudioRecord = new AudioRecord(
mAudioSource, mSampleRateHz, channelConfig, mAudioEncoding, bufferSize);// The RAW PCM sample recording
if (mAudioRecord.getState() != AudioRecord.STATE_INITIALIZED) {
Log.e(TAG,"AudioRecord init failed");
return;
}
final short[] buffer = new short[mBlockSize];
mAudioRecord.startRecording();
int len = 0;
while (mbExit == false) {
len = mAudioRecord.read(buffer, 0, mBlockSize);
if (len < 0) {
Log.e(TAG,"read error " + len);
return;
}
}
mAudioRecord.stop();
mAudioRecord.release();
}
It should work now!
Android AudioRecord - Won't Initialize 2nd time
I was able to reproduce your problem (on a Samsung phone). I added an onDestroy() method releasing the record:
@Override
public void onDestroy() {
super.onDestroy();
System.out.println("OnDestroy");
audRec.release();
}
After adding this, the audioRecord seems to initialize correctly every time the activity is started.
AudioRecord can not be initialized
Try this instead:
private MediaRecorder mRecorder = null;
private void startRecording() {
String fileSaveName = generateNameForAudioFile();
mRecorder = new MediaRecorder();
mRecorder.setAudioSource(MediaRecorder.AudioSource.MIC);
mRecorder.setOutputFormat(MediaRecorder.OutputFormat.THREE_GPP);
mRecorder.setOutputFile(fileSaveName);
mRecorder.setAudioEncoder(MediaRecorder.AudioEncoder.DEFAULT);
try {
mRecorder.prepare();
} catch (IOException e) {
Log.e(LOG_TAG, "prepare() failed");
}
mRecorder.start();
}
private void stopRecording() {
startRecording.setEnabled(true);
try {
if (mRecorder != null) {
mRecorder.stop();
mRecorder.release();
mRecorder = null;
}
} catch (Exception e) {
}
}
public String generateNameForAudioFile() {
String audioName = GetrandFilename();
mFileName = Environment.getExternalStorageDirectory().getPath() + "/"
+ audioName + "myaudio" + ".3gp";
);
return mFileName;
}
@Override
public void onPause() {
super.onPause();
try {
if (mRecorder != null) {
mRecorder.stop();
mRecorder.release();
mRecorder = null;
}
} catch (Exception e) {
}
}
Let me know if this post is of any help.
Related Topics
How to Add a Badge to an Application Icon in Android
Arrayadapter in Android to Create Simple Listview
Android Ndk: Getting the Backtrace
How to Set Versionname in APK Filename Using Gradle
How to Take a Screenshot of a Current Activity and Then Share It
Android: Speech Recognition Without Using Google Server
Show an Alert Dialog in Broadcast Receiver After a System Reboot
Using the Recyclerview with a Database
Android SQLite Db When to Close
Android Spinner:Avoid Onitemselected Calls During Initialization
Listview Getchildat Returning Null for Visible Children
How to Get the List of Running Applications
Get Spinner Selected Items Text
How to Prevent Android Bluetooth Rfcomm Connection from Dying Immediately After .Connect()
Listview with Onitemclicklistener