I am trying to work with audiorecorder, but I am getting illegal argument exceptions stating that the audiorecorder is not initialised.
My code is like the one shown here
private static final int RECORDER_SAMPLERATE = 44100;
private static final int RECORDER_CHANNELS = AudioFormat.CHANNEL_IN_STEREO;
private static final int RECORDER_AUDIO_ENCODING = AudioFormat.ENCODING_PCM_16BIT;
recorder = new AudioRecord(MediaRecorder.AudioSource.MIC,RECORDER_SAMPLERATE, RECORDER_CHANNELS,RECORDER_AUDIO_ENCODING, bufferSize);
recorder.startRecording();
I have seen another answer which seems to work for some people but it isn't working for me
AudioRecord object not initializing
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.
I was actually doing the silly thing I was giving the permissions inside application tag corrected it and it's working fine thanks everyone for the time and support
Related
I am very new to android development and I don't have enough experience. So the question I am asking might be very simple. I want to detect if there is noise in the environment using microphone. Now if there is no mic on the cellphone I will toast a relevant.
I found the code from here: android: Detect sound level
On main activity I have a button. Pressing the button will toast some result. But I only get 0.0 even though there is a noise in the room. Could some one give me some hint on this please.
public class MainActivity extends AppCompatActivity implements SensorEventListener {
double soundLevel;
protected void onCreate(Bundle savedInstanceState) {
noiseButton = findViewById(R.id.noiseCheck);
PackageManager PM= this.getPackageManager();
final boolean microphone = PM.hasSystemFeature(PackageManager.FEATURE_MICROPHONE);
noiseButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
if (microphone){
double soundLevel = detectEnvironmentalNoise();
Toast.makeText(mContext, "Environmental noise level is " + soundLevel , Toast.LENGTH_LONG).show();
}
else{
Toast.makeText(mContext, "This device is not equipped to microphone to detect environmental noise", Toast.LENGTH_LONG).show();
}
}
});
}
public double detectEnvironmentalNoise() {
AudioRecord audio = null;
int sampleRate = 8000;
double lastLevel = 0;
try {
int bufferSize = AudioRecord.getMinBufferSize(sampleRate, AudioFormat.CHANNEL_IN_MONO,
AudioFormat.ENCODING_PCM_16BIT);
audio = new AudioRecord(MediaRecorder.AudioSource.MIC, sampleRate,
AudioFormat.CHANNEL_IN_MONO,
AudioFormat.ENCODING_PCM_16BIT, bufferSize);
} catch (Exception e) {
android.util.Log.e("TrackingFlow", "Exception", e);
}
audio.startRecording();
short[] buffer = new short[100];
int bufferReadResult = 1;
if (audio != null) {
// Sense the voice...
bufferReadResult = audio.read(buffer, 0, 10000);
double sumLevel = 0;
for (int i = 0; i < bufferReadResult; i++) {
sumLevel += buffer[i];
}
lastLevel = Math.abs((sumLevel / bufferReadResult));
}
return lastLevel;
}
}
You need to implement getMaxAmplitude() for AudioRecord as described in below post:
Implement getMaxAmplitude for audioRecord
Or you can use MediaRecorder as below:
public class SoundMeter {
private MediaRecorder mRecorder = null;
public void start() {
if (mRecorder == null) {
mRecorder = new MediaRecorder();
mRecorder.setAudioSource(MediaRecorder.AudioSource.MIC);
mRecorder.setOutputFormat(MediaRecorder.OutputFormat.THREE_GPP);
mRecorder.setAudioEncoder(MediaRecorder.AudioEncoder.AMR_NB);
mRecorder.setOutputFile("/dev/null");
mRecorder.prepare();
mRecorder.start();
}
}
public void stop() {
if (mRecorder != null) {
mRecorder.stop();
mRecorder.release();
mRecorder = null;
}
}
public double getAmplitude() {
if (mRecorder != null)
return mRecorder.getMaxAmplitude();
else
return 0;
}
}
First time when i run this code it runs fine but when i pause and play it again mainthread stop for more than or equal to 20 second and then show ANR dialog and after that it didn't start again.Reviewed this code many time but not able to debug.I also comment startRecording() and stopRecording() but after that it runs okay i.e, the problem is in starting and stopping the service.
public class RecordingService extends Service {
private String filePath = null;
private String dateSuffix = null;
private MediaRecorder mediaRecorder = null;
private DatabaseHelperClass databaseHelperClass;
#Override
public IBinder onBind(Intent intent) {
return null;
}
#Override
public void onCreate() {
super.onCreate();
databaseHelperClass = new DatabaseHelperClass(getApplicationContext());
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
startRecording();
return START_STICKY;
}
#Override
public void onDestroy() {
stopRecording();
super.onDestroy();
}
private void stopRecording() {
try {
if (mediaRecorder != null) {
mediaRecorder.stop();
mediaRecorder.release();
mediaRecorder = null;
}
}
catch (IllegalStateException e){
}
}
private void startRecording() {
if (mediaRecorder != null)
mediaRecorder.release();
pathCreater();
mediaRecorder = new MediaRecorder();
mediaRecorder.setAudioSource(MediaRecorder.AudioSource.MIC);
mediaRecorder.setOutputFormat(MediaRecorder.OutputFormat.MPEG_4);
mediaRecorder.setAudioEncoder(MediaRecorder.AudioEncoder.AAC);
mediaRecorder.setAudioChannels(1);
mediaRecorder.setOutputFile(filePath);
try {
mediaRecorder.prepare();
mediaRecorder.start();
} catch (IOException e) {
e.printStackTrace();
}
}
private void pathCreater() {
String fileName;
File file;
SimpleDateFormat simpleDateFormat = new SimpleDateFormat("MMM MM dd, yyyy h:mm a");
long date = System.currentTimeMillis();
dateSuffix = simpleDateFormat.format(date);
do {
fileName = getString(R.string.file_name_suffix) + "_" + dateSuffix + ".mp3";
filePath = Environment.getExternalStorageDirectory().getAbsolutePath();
filePath += "/" + fileName;
file = new File(filePath);
} while (file.exists() && !file.isDirectory());
}
}
Hey I'm trying to record a screencast app in android lolipop using mediarecorder api. Problem is that my application acts weird. Whenever I call start recording on the VideoRecorder class even when hardcoding the configuration like video size and output file the phone reboots. The app previosuly worked fine - saved the stuff in the correct place and the video itself looked good but then I've changed something in the code and now it doesn't work. Any idea what I'm missing?
Here is my code:
public class VideoRecorder {
private int screenDensity, screenHeight, screenWidth;
private MediaRecorder mMediaRecorder;
private VirtualDisplay mVirtualDisplay;
private MediaProjection mediaProjection;
private String directory, filename;
private Display defaultDisplay = null;
private DisplayMetrics metrics;
public VideoRecorder(Display defaultDisplay) {
//this.defaultDisplay = defaultDisplay;
//metrics = new DisplayMetrics();
//defaultDisplay.getMetrics(metrics);
//screenDensity = metrics.densityDpi;
// screenHeight = metrics.heightPixels;
// screenWidth = metrics.widthPixels;
}
void prepareVideoRecorder() {
initRecorder();
prepareRecorder();
}
private void initRecorder() {
mMediaRecorder.setAudioSource(MediaRecorder.AudioSource.MIC);
mMediaRecorder.setVideoSource(MediaRecorder.VideoSource.SURFACE);
mMediaRecorder.setOutputFormat(MediaRecorder.OutputFormat.MPEG_4);
mMediaRecorder.setVideoEncoder(MediaRecorder.VideoEncoder.H264);
mMediaRecorder.setAudioEncoder(MediaRecorder.AudioEncoder.AMR_NB);
mMediaRecorder.setVideoEncodingBitRate(512 * 1000);
mMediaRecorder.setVideoFrameRate(30);
mMediaRecorder.setVideoSize(540, 888);
// mMediaRecorder.setOutputFile(directory + "/" + filename + ".mp4");
mMediaRecorder.setOutputFile(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_MOVIES).getAbsoluteFile() + "/recorderrsr.mp4");
}
void startRecording(MediaProjection mediaProjection) {
mMediaRecorder = new MediaRecorder();
initRecorder();
prepareRecorder();
this.mediaProjection = mediaProjection;
mMediaRecorder.start();
mVirtualDisplay = createVirtualDisplay();
}
private VirtualDisplay createVirtualDisplay() {
return mediaProjection.createVirtualDisplay("MainActivity",
540, 888, 240,
DisplayManager.VIRTUAL_DISPLAY_FLAG_AUTO_MIRROR,
mMediaRecorder.getSurface(), null /*Callbacks*/, null /*Handler*/);
}
void setFilename(String filename) {
this.filename = filename;
}
void setDirectory(String directory) {
this.directory = directory;
}
void stopRecording() {
mMediaRecorder.stop();
mMediaRecorder.reset();
if (mediaProjection != null) {
mediaProjection.stop();
mediaProjection = null;
}
if (mMediaRecorder != null) {
mMediaRecorder.release();
mMediaRecorder = null;
}
if (mVirtualDisplay != null) {
mVirtualDisplay.release();
}
}
private void prepareRecorder() {
try {
mMediaRecorder.prepare();
} catch (IllegalStateException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
void release() {
mMediaRecorder.release();
}
}
I'm sure that the location exists and I have the correct permissions - as I've said the app worked fine before.
Thanks for help Jon
I am working on an android application . I am recording audio using MediaRecorder class. I want to check size of recorded audio while recording and check size of recorded audio if size greater than certain MB I want stop recording . How can I achieve this . any help will be appreciated .
public class RecordAudio {
private MediaRecorder mRecorder = null;
public RecordAudio() {
}
//
public void prepareRecording(String fileName) {
if (mRecorder == null) {
mRecorder = new MediaRecorder();
}
if (mRecorder != null) {
mRecorder.setAudioSource(MediaRecorder.AudioSource.MIC);
mRecorder.setOutputFormat(MediaRecorder.OutputFormat.THREE_GPP);
mRecorder.setOutputFile(app.appExternalDir + "/" + fileName);
mRecorder.setAudioEncoder(MediaRecorder.AudioEncoder.AMR_NB);
System.out.println("this is max::::"+mRecorder.getAudioSourceMax());
try {
mRecorder.prepare();
} catch (IOException e) {
}
}
}
// This starts the recording of the voice memo
public void startRecording() {
if (mRecorder != null) {
mRecorder.start();
}
}
// This stops the recording and save the data on storage
public void stopRecording() {
if (mRecorder != null) {
mRecorder.stop();
mRecorder.release();
mRecorder = null;
}
}
}
use below code to get size of your recorded file
try{
File file = new File(path_of_your_recorded_file);
long length = file.length();
length = length/1024;
System.out.println("File Path : " + file.getPath() + ", File size : " + length +" KB");
}catch(Exception e){
System.out.println("File not found : " + e.getMessage() + e);
}
then once you get length you can chek as per your requirement hope it will solve your problem
For those who came across this now:
There is an Interface that you can implement :
public class RecordingService extends Service implements
MediaRecorder.OnInfoListener{
#Override
public void onInfo(MediaRecorder mr, int what, int extra) {
Log.d(TAG_FOREGROUND_SERVICE,"inside the onInfo");
//check whether file size has reached to Max size to stop recording
if (what == MediaRecorder.MEDIA_RECORDER_INFO_MAX_FILESIZE_REACHED)
{
Log.d(TAG_FOREGROUND_SERVICE,"Media exceeded the size");
}
}
}
And In your MediaRecorder initialisation code you can set the interface callback and size
eg:
mRecorder = new MediaRecorder();
mRecorder.setOnInfoListener(this);
mRecorder.setAudioSource(MediaRecorder.AudioSource.MIC);
mRecorder.setMaxFileSize(Audio_MAX_FILE_SIZE);
Hope it helps
I am making an android application to record sound. I have been using class MediaRecorder for that.
The recording is done successfully when the recording is done for the first time on any device. But it doesn't work next time.
If I try the code on another machine, recording is done successfully. Is it so because MediaRecorder instance is not getting released by the app even if I am calling method release().
This is my code-
public class NewClass extends Activity {
private static String sFileName = null;
private static String sFileNameMSD = null;
private static String sPlayFile = null;
public MediaRecorder mRecorder = null;
private String mPn_id;
private String mDescription;
private String mTask_flag;
private String mPatient_name;
private String mPatient_id;
private String mIs_upload = "N";
private Context mContext;
Button btnStart;
Button btnStop;
private int mReuqestcode;
NewClass myActivity;
SeekBar seekBar;
int totalTime;
private final Handler handler = new Handler();
private final String FILE_EXTENTION_AMR = ".amr";
private final String FILE_EXTENTION_MSD = ".msd";
protected boolean recodeFlag = false;;
private static final String TAG = GridAllActivity.class.getName();
#Override
public void onCreate(Bundle icicle) {
super.onCreate(icicle);requestWindowFeature(Window.FEATURE_CUSTOM_TITLE);
setContentView(R.layout.transcriptionrecord_activity);
mContext = this;
myActivity = this;
Main.setTitle(myActivity, mContext);
Thread.setDefaultUncaughtExceptionHandler(new CustomExceptionHandler(
mContext));
TextView txtTitle = (TextView) findViewById(R.id.txt_Title1);
txtTitle.setText("Transcription");
TextView txtOption = (TextView) findViewById(R.id.txtOptionName);
TextView txtPatientName = (TextView) findViewById(R.id.txtPatientName);
setProperty();
txtOption.setText("" + mDescription);
txtPatientName.setText("" + mPatient_name);
}
private void onRecord(boolean start) throws SettingNotFoundException {
if (start) {
startRecording();
} else {
stopRecording();
}
}
private void startRecording() throws SettingNotFoundException {
mRecorder = new MediaRecorder();
mRecorder.setAudioSource(MediaRecorder.AudioSource.MIC);
mRecorder.setOutputFormat(MediaRecorder.OutputFormat.RAW_AMR);
mRecorder.setOutputFile(sFileName);
mRecorder.setAudioEncoder(MediaRecorder.AudioEncoder.AMR_NB);
try {
mRecorder.prepare();
mRecorder.start();
} catch (IOException e) {
recodeFlag=true;
Log.e("1", "prepare() failed");
e.printStackTrace();
}
}
private void stopRecording() throws SettingNotFoundException {
mRecorder.stop();
mRecorder.release();
Log.d("1", "mRecorder released");
mRecorder = null;
System.gc();
}
public void setRecordPath() throws IOException {
sFileName = Environment.getExternalStorageDirectory().getAbsolutePath();
sFileName += Global.creteFolderPath("IMSEMR" + mTask_flag + "_"
+ mPn_id + FILE_EXTENTION_AMR);
sFileNameMSD = "IMSEMR" + mTask_flag + "_" + mPn_id
+ FILE_EXTENTION_MSD;
String state = android.os.Environment.getExternalStorageState();
if (!state.equals(android.os.Environment.MEDIA_MOUNTED)) {
Global.alertbox("", "SD Card is not mounted.", mContext);
throw new IOException("SD Card is not mounted. It is " + state
+ ".");
}
File directory = new File(sFileName).getParentFile();
if (!directory.exists() && !directory.mkdirs()) {
directory.mkdirs();
throw new IOException("Path to file could not be created.");
}
}
public void setRecodingLayout() {
btnStop.setEnabled(false);
try {
btnStart.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
boolean mStartRecording = true;
try {
btnStop.setEnabled(true);
btnStart.setEnabled(false);
onRecord(mStartRecording);
} catch (SettingNotFoundException e) {
e.printStackTrace();
}
}
});
btnStop.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
try {
boolean mStartRecording = false;
try {
onRecord(mStartRecording);
} catch (SettingNotFoundException e) {
e.printStackTrace();
}
} catch (SQLiteException e) {
// TODO: handle exception
} catch (Exception e) {
// TODO: handle exception
}
}
});
} catch (NullPointerException e) {
}
}
public void setProperty() {
Bundle bundel = getIntent().getExtras();
mReuqestcode = (Integer) bundel.get("REQUEST_CODE");
// property for Record
if (mReuqestcode == 1) {
mPn_id = (String) bundel.get("PN_ID");
mDescription = (String) bundel.get("DESCRIPTION");
mTask_flag = (String) bundel.get("TASK_FLAG");
mPatient_id = (String) bundel.get("PATIENT_ID");
mPatient_name = (String) bundel.get("PATIENT_NAME");
btnStart = (Button) findViewById(R.id.btnStart);
btnStop = (Button) findViewById(R.id.btnStop);
btnStop.setEnabled(false);
setRecodingLayout();
try {
setRecordPath();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
You need to create a new instance of media recorder each time you want to record (making sure to release the previous one).
Update --
Sorry, you only need to create a new instance if you call release on the object. Otherwise you can just call reset,
read this: http://developer.android.com/reference/android/media/MediaRecorder.html
Example:
Lets say you have an activity with 2 buttons, a record button and a play button
public class MyRecordDemo extends Activity {
private static final String PATH_NAME = "/sdcard/myfile.3gp"; //probably shouldn't hardcode this
private Button mRecordButton, mStopButton;
private MediaRecorder mRecorder = null;
private boolean mIsRecording = false;
public void onCreate(Bundle state) {
super.onCreate(state);
setContentView(R.layout.recorder_demo);
mRecordButton = (Button) findViewById(R.id.record_btn);
mStopButton = (Button) findViewById(R.id.stop_btn);
mStopButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
if (mIsRecording && mRecorder != null) {
mRecorder.stop();
mRecorder.release();
}
}
});
mRecordButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
if (mIsRecording && mRecorder != null) {
mRecorder.stop();
mRecorder.release();
}
mRecorder = new MediaRecorder();
mRecorder.setAudioSource(MediaRecorder.AudioSource.MIC);
mRecorder.setOutputFormat(MediaRecorder.OutputFormat.THREE_GPP);
mRecorder.setAudioEncoder(MediaRecorder.AudioEncoder.AMR_NB);
mRecorder.setOutputFile(PATH_NAME);
mRecorder.prepare();
mRecorder.start()
}
});
}
}