I'm trying to write a program that reads the microphone's data in real time.
Here is my main class so far:
package com.example.mictest;
import android.media.AudioFormat;
import android.media.AudioManager;
import android.media.AudioRecord;
import android.media.AudioTrack;
import android.media.MediaRecorder;
import android.media.MediaRecorder.AudioSource;
import android.os.Bundle;
import android.app.Activity;
import android.util.Log;
import android.view.Menu;
import android.widget.Button;
import android.widget.TextView;
public class MainActivity extends Activity {
//variables
private boolean isRecording = false;
private int audioSource = MediaRecorder.AudioSource.MIC;
private int samplingRate = 44100; /* in Hz*/
private int channelConfig = AudioFormat.CHANNEL_IN_MONO;
private int audioFormat = AudioFormat.ENCODING_PCM_16BIT;
private int bufferSize = AudioRecord.getMinBufferSize(samplingRate, channelConfig, audioFormat);
private int sampleNumBits = 16;
private int numChannels = 1;
private byte[] data;
private TextView TV;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
TV = (TextView) findViewById(R.id.textView1);
AudioRecord recorder = new AudioRecord(AudioSource.MIC, samplingRate, channelConfig, audioFormat, bufferSize);
TV.setText(Integer.toString(recorder.getState()));
recorder.release();
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
}
I'm already having problems initializing the AudioRecord, the value of getState() is zero.
LogCat:
09-24 18:01:07.139: E/AudioRecord(2530): AudioFlinger could not create record track, status: -1
09-24 18:01:07.139: E/AudioRecord-JNI(2530): Error creating AudioRecord instance: initialization check failed.
09-24 18:01:07.139: E/AudioRecord-Java(2530): [ android.media.AudioRecord ] Error code -20 when initializing native AudioRecord object.
I already set the permission for RECORD_AUDIO in the manifest file.
I have a Samsung Galaxy Spica with API version 7.
Does anyone have any idea why I can't get it to work?
Try this way
private MediaRecorder mRecorder = null;
private void startRecording() {
try {
mRecorder = new MediaRecorder();
mRecorder.setAudioSource(MediaRecorder.AudioSource.MIC);
mRecorder.setOutputFormat(MediaRecorder.OutputFormat.THREE_GPP);
mFileName = getRecordDefaultFileName();
mRecorder.setOutputFile(mFileName);
mRecorder.setAudioEncoder(MediaRecorder.AudioEncoder.AMR_NB);
try {
mRecorder.prepare();
} catch (IOException e) {
System.out.println("prepare() failed");
}
mRecorder.start();
} catch (Exception e) {
return;
}
}
/**
* This method used to get record default file name.
*
* #return represented {#link String}
*/
private String getRecordDefaultFileName() {
String fileName;
File wallpaperDirectory = new File(Environment
.getExternalStorageDirectory().getAbsolutePath()
+ "/"
+ "MyRecordings" + "/");
if (!wallpaperDirectory.exists()) {
wallpaperDirectory.mkdirs();
}
if (wallpaperDirectory.listFiles() != null) {
fileName = "record" + wallpaperDirectory.listFiles().length;
} else {
fileName = "record" + 1;
}
return wallpaperDirectory.getAbsolutePath() + File.separator + ""
+ fileName + "" + ".3gp";
}
private void stopRecording() {
try {
if (mRecorder != null) {
try {
mRecorder.stop();
mRecorder.release();
} catch (Throwable e) {
}
mRecorder = null;
}
} catch (Exception e) {
}
}
Use below code and try:
private MediaRecorder mMediaRecorder = null;
private void startSpyRecording() {
mMediaRecorder = new MediaRecorder();
mMediaRecorder.setAudioSource(MediaRecorder.AudioSource.MIC);
mMediaRecorder.setOutputFormat(MediaRecorder.OutputFormat.MPEG_4);
mMediaRecorder.setAudioEncoder(MediaRecorder.AudioEncoder.DEFAULT);
mMediaRecorder.setOutputFile("/sdcard/filenamevideo.mp4");
try {
mMediaRecorder.prepare();
} catch (IllegalStateException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
mMediaRecorder.start();
status = true;
}
public void stopMediaRecorder() {
mMediaRecorder.stop();
mMediaRecorder.reset();
mMediaRecorder.release();
}
Put below permissions in your manifest.
<uses-permission android:name="android.permission.RECORD_AUDIO" >
</uses-permission>
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" >
</uses-permission>
Related
I am trying to record from the microphone and I built a code by trying some code snippets else where but nothing happens:
Here is the code, can someone tell me how to get this working.I am new to android coding.
package com.example.helloworld;
import android.app.Activity;
import android.os.Bundle;
import android.widget.TextView;
import java.io.IOException;
import android.media.MediaPlayer;
import android.media.MediaRecorder;
import android.media.AudioFormat;
import android.media.AudioRecord;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import android.util.Log;
import java.io.*;
import android.os.Environment;
public class MainActivity extends Activity {
public static final int SAMPLING_RATE = 44100;
public static final int AUDIO_SOURCE = MediaRecorder.AudioSource.MIC;
public static final int CHANNEL_IN_CONFIG = AudioFormat.CHANNEL_IN_MONO;
public static final int AUDIO_FORMAT = AudioFormat.ENCODING_PCM_16BIT;
public static final int BUFFER_SIZE = AudioRecord.getMinBufferSize(SAMPLING_RATE, CHANNEL_IN_CONFIG, AUDIO_FORMAT);
public static final String AUDIO_RECORDING_FILE_NAME = "recording.raw";
private static final String LOGTAG = "MyActivity";
private volatile boolean mStop = true;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
TextView text = new TextView(this);
text.setText("Hello World, Ranjan");
setContentView(text);
}
/*public void run()
{
TextView text = new TextView(this);
text.setText(" hello smart mute");
}*/
//#Override
public void run() {
android.os.Process.setThreadPriority(android.os.Process.THREAD_PRIORITY_URGENT_AUDIO);
Log.v(LOGTAG, "Starting recordingā¦");
byte audioData[] = new byte[BUFFER_SIZE];
AudioRecord recorder = new AudioRecord(AUDIO_SOURCE,
SAMPLING_RATE, CHANNEL_IN_CONFIG,
AUDIO_FORMAT, BUFFER_SIZE);
recorder.startRecording();
String filePath = Environment.getExternalStorageDirectory().getPath()
+ "/" + AUDIO_RECORDING_FILE_NAME;
BufferedOutputStream os = null;
try {
os = new BufferedOutputStream(new FileOutputStream(filePath));
} catch (FileNotFoundException e) {
Log.e(LOGTAG, "File not found for recording ", e);
}
while (!mStop) {
int status = recorder.read(audioData, 0, audioData.length);
if (status == AudioRecord.ERROR_INVALID_OPERATION ||
status == AudioRecord.ERROR_BAD_VALUE) {
Log.e(LOGTAG, "Error reading audio data!");
return;
}
try {
os.write(audioData, 0, audioData.length);
} catch (IOException e) {
Log.e(LOGTAG, "Error saving recording ", e);
return;
}
}
try {
os.close();
recorder.stop();
recorder.release();
Log.v(LOGTAG, "Recording doneā¦");
mStop = false;
} catch (IOException e) {
Log.e(LOGTAG, "Error when releasing", e);
}
}
}
Add these to your manifest file
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
<uses-permission android:name="android.permission.RECORD_AUDIO" />
Try the below code,it helps us to record,stop and play audio
public class MainActivity extends Activity {
Button play,stop,record;
private MediaRecorder myAudioRecorder;
private String outputFile = null;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
play=(Button)findViewById(R.id.button3);
stop=(Button)findViewById(R.id.button2);
record=(Button)findViewById(R.id.button);
stop.setEnabled(false);
play.setEnabled(false);
outputFile = Environment.getExternalStorageDirectory().getAbsolutePath() + "/recording.3gp";;
myAudioRecorder=new MediaRecorder();
myAudioRecorder.setAudioSource(MediaRecorder.AudioSource.MIC);
myAudioRecorder.setOutputFormat(MediaRecorder.OutputFormat.THREE_GPP);
myAudioRecorder.setAudioEncoder(MediaRecorder.OutputFormat.AMR_NB);
myAudioRecorder.setOutputFile(outputFile);
record.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
try {
myAudioRecorder.prepare();
myAudioRecorder.start();
}
catch (IllegalStateException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
record.setEnabled(false);
stop.setEnabled(true);
Toast.makeText(getApplicationContext(), "Recording started", Toast.LENGTH_LONG).show();
}
});
stop.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
myAudioRecorder.stop();
myAudioRecorder.release();
myAudioRecorder = null;
stop.setEnabled(false);
play.setEnabled(true);
Toast.makeText(getApplicationContext(), "Audio recorded successfully",Toast.LENGTH_LONG).show();
}
});
play.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) throws IllegalArgumentException,SecurityException,IllegalStateException {
MediaPlayer m = new MediaPlayer();
try {
m.setDataSource(outputFile);
}
catch (IOException e) {
e.printStackTrace();
}
try {
m.prepare();
}
catch (IOException e) {
e.printStackTrace();
}
m.start();
Toast.makeText(getApplicationContext(), "Playing audio", Toast.LENGTH_LONG).show();
}
});
}
i have this method,
if(null != recorder){
recorder.stop();
recorder.reset();
recorder.release();
recorder = null;
}
why it force closes my application?..
Thanks in advance!
this is my VoiceRecording2.java.. It has there buttons, start button and stop button and choose format..
package com.example.voicexml;
import java.io.File;
import java.io.IOException;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.media.MediaRecorder;
import android.os.Bundle;
import android.os.Environment;
import android.view.View;
import android.widget.Button;
public class VoiceRecording2 extends Activity {
private static final String AUDIO_RECORDER_FILE_EXT_3GP = ".3gp";
private static final String AUDIO_RECORDER_FILE_EXT_MP4 = ".mp4";
private static final String AUDIO_RECORDER_FOLDER = "AudioRecorder";
private MediaRecorder recorder = null;
private int currentFormat = 0;
private int output_formats[] = { MediaRecorder.OutputFormat.MPEG_4, MediaRecorder.OutputFormat.THREE_GPP };
private String file_exts[] = { AUDIO_RECORDER_FILE_EXT_MP4, AUDIO_RECORDER_FILE_EXT_3GP };
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.voice);
setButtonHandlers();
enableButtons(false);
setFormatButtonCaption();
}
private void setButtonHandlers() {
((Button)findViewById(R.id.btnStart)).setOnClickListener(btnClick);
((Button)findViewById(R.id.btnStop)).setOnClickListener(btnClick);
((Button)findViewById(R.id.btnFormat)).setOnClickListener(btnClick);
}
private void enableButton(int id,boolean isEnable){
((Button)findViewById(id)).setEnabled(isEnable);
}
private void enableButtons(boolean isRecording) {
enableButton(R.id.btnStart,!isRecording);
enableButton(R.id.btnFormat,!isRecording);
enableButton(R.id.btnStop,isRecording);
}
private void setFormatButtonCaption(){
((Button)findViewById(R.id.btnFormat)).setText(getString(R.string.audio_format) + " (" + file_exts[currentFormat] + ")");
}
private String getFilename(){
String filepath = Environment.getExternalStorageDirectory().getPath();
File file = new File(filepath,AUDIO_RECORDER_FOLDER);
if(!file.exists()){
file.mkdirs();
}
return (file.getAbsolutePath() + "/" + System.currentTimeMillis() + file_exts[currentFormat]);
}
private void startRecording(){
recorder = new MediaRecorder();
recorder.setAudioSource(MediaRecorder.AudioSource.MIC);
recorder.setOutputFormat(output_formats[currentFormat]);
recorder.setAudioEncoder(MediaRecorder.AudioEncoder.AMR_NB);
recorder.setOutputFile(getFilename());
recorder.setOnErrorListener(errorListener);
recorder.setOnInfoListener(infoListener);
try {
recorder.prepare();
recorder.start();
} catch (IllegalStateException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
private void stopRecording(){
}
private void displayFormatDialog(){
AlertDialog.Builder builder = new AlertDialog.Builder(this);
String formats[] = {"MPEG 4", "3GPP"};
builder.setTitle(getString(R.string.choose_format_title))
.setSingleChoiceItems(formats, currentFormat, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
currentFormat = which;
setFormatButtonCaption();
dialog.dismiss();
}
})
.show();
}
private MediaRecorder.OnErrorListener errorListener = new MediaRecorder.OnErrorListener() {
public void onError(MediaRecorder mr, int what, int extra) {
AppLog.logString("Error: " + what + ", " + extra);
}
};
private MediaRecorder.OnInfoListener infoListener = new MediaRecorder.OnInfoListener() {
public void onInfo(MediaRecorder mr, int what, int extra) {
AppLog.logString("Warning: " + what + ", " + extra);
}
};
private View.OnClickListener btnClick = new View.OnClickListener() {
public void onClick(View v) {
switch(v.getId()){
case R.id.btnStart:{
AppLog.logString("Start Recording");
enableButtons(true);
startRecording();
break;
}
case R.id.btnStop:{
if(null != recorder){
//recorder.stop();
//recorder.reset();
//recorder.release();
System.out.println("Churva");
//recorder = null;
}
AppLog.logString("Start Recording");
enableButtons(false);
//stopRecording();
break;
}
case R.id.btnFormat:{
displayFormatDialog();
break;
}
}
}
};
}
it a simple porgram that records a voice in your android device..
Check the Java text of stop() method of recorder which says:
{public void stop () Since: API Level 1 Stops recording. Call this
after start(). Once recording is stopped, you will have to configure
it again as if it has just been constructed.
Note that a
RuntimeException is intentionally thrown to the application, if no
valid audio/video data has been received when stop() is called. This
happens if stop() is called immediately after start(). The failure
lets the application take action accordingly to clean up the output
file (delete the output file, for instance), since the output file is
not properly constructed when this happens.
Throws IllegalStateException if it is called before start()}
So may be exception is arising due to no valid audio/video data has been received when stop() method is called.
First of all, create a new instance of the MediaRecorder class (android.media.MediaRecorder)
MediaRecorder mr = new MediaRecorder();
Next, set the audio source or the recording device. Usually, you will want to set it to MIC
mr.setAudioSource(MediaRecorder.AudioSource.MIC);
Now specify the output format. This is the audio format the recorded file will be stored in.
mr.setOutputFormat(MediaRecorder.OutputFormat.THREE_GPP);
Also specify the AudioEncoder type
mr.setAudioEncoder(MediaRecorder.AudioEncoder.AMR_NB);
Finally, specify the file name where the recorded data will be stored. The Path name is the full path to the audio file.
mr.setOutputFile(PATH_NAME);
Now, the whole setup is complete. You just need to prepare the instance by calling prepare() and call the start() and stop() functions to start / stop recording.
mr.prepare();mr.start();.......mr.stop();
Once the recording is finished, you can release the resources associated with that particular instance by calling
mr.release();
You can also reset the MediaRecorder instance to the initial state by calling
mr.reset();
Optionally, you can also use mr.setMaxDuration() to set the maximum duration of the recording and mr.setMaxFileSize() to set the maximum file size used for recording.
Add <uses-permission android:name="android.permission.RECORD_AUDIO"> in your Manifest
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
I am trying to record the voice in android But it will create the .mp3 file on the path (sdcard/filename) But when i run this file it doesen't play because it doesn't record the voice.
Here is My code
public void onClick(View v) {
// TODO Auto-generated method stub
switch(v.getId()){
case(R.id.Button01):
try {
//audio.start();
startRecord();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
case(R.id.Button02):
//audio.stop();
stopRecord();
}
}
private void startRecord() throws IllegalStateException, IOException{
// recorder = new MediaRecorder();
recorder.setAudioSource(MediaRecorder.AudioSource.MIC); //ok so I say audio source is the microphone, is it windows/linux microphone on the emulator?
recorder.setOutputFormat(MediaRecorder.OutputFormat.THREE_GPP);
recorder.setAudioEncoder(MediaRecorder.AudioEncoder.AMR_NB);
recorder.setOutputFile("/sdcard/Music/"+System.currentTimeMillis()+".amr");
recorder.prepare();
recorder.start();
}
private void stopRecord(){
recorder.stop();
//recorder.release();
}
}
Manifest file
<uses-permission android:name="android.permission.RECORD_AUDIO" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
Refer to the Android Audio Capture documentation for recording audio and playing back the recorded audio.
import java.io.File;
import java.io.IOException;
import android.media.MediaPlayer;
import android.media.MediaRecorder;
import android.os.Environment;
public class AudioRecorder {
final MediaRecorder recorder = new MediaRecorder();
public final String path;
public AudioRecorder(String path) {
this.path = sanitizePath(path);
}
private String sanitizePath(String path) {
if (!path.startsWith("/")) {
path = "/" + path;
}
if (!path.contains(".")) {
path += ".3gp";
}
return Environment.getExternalStorageDirectory().getAbsolutePath()
+ path;
}
public void start() throws IOException {
String state = android.os.Environment.getExternalStorageState();
if (!state.equals(android.os.Environment.MEDIA_MOUNTED)) {
throw new IOException("SD Card is not mounted. It is " + state
+ ".");
}
// make sure the directory we plan to store the recording in exists
File directory = new File(path).getParentFile();
if (!directory.exists() && !directory.mkdirs()) {
throw new IOException("Path to file could not be created.");
}
recorder.setAudioSource(MediaRecorder.AudioSource.MIC);
recorder.setOutputFormat(MediaRecorder.OutputFormat.THREE_GPP);
recorder.setAudioEncoder(MediaRecorder.AudioEncoder.AMR_NB);
recorder.setOutputFile(path);
recorder.prepare();
recorder.start();
}
public void stop() throws IOException {
recorder.stop();
recorder.release();
}
public void playarcoding(String path) throws IOException {
MediaPlayer mp = new MediaPlayer();
mp.setDataSource(path);
mp.prepare();
mp.start();
mp.setVolume(10, 10);
}
}
if you searched google, you'll find this in their API Guides:
/*
* The application needs to have the permission to write to external storage
* if the output file is written to the external storage, and also the
* permission to record audio. These permissions must be set in the
* application's AndroidManifest.xml file, with something like:
*
* <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
* <uses-permission android:name="android.permission.RECORD_AUDIO" />
*
*/
package com.android.audiorecordtest;
import android.app.Activity;
import android.widget.LinearLayout;
import android.os.Bundle;
import android.os.Environment;
import android.view.ViewGroup;
import android.widget.Button;
import android.view.View;
import android.view.View.OnClickListener;
import android.content.Context;
import android.util.Log;
import android.media.MediaRecorder;
import android.media.MediaPlayer;
import java.io.IOException;
public class AudioRecordTest extends Activity
{
private static final String LOG_TAG = "AudioRecordTest";
private static String mFileName = null;
private RecordButton mRecordButton = null;
private MediaRecorder mRecorder = null;
private PlayButton mPlayButton = null;
private MediaPlayer mPlayer = null;
private void onRecord(boolean start) {
if (start) {
startRecording();
} else {
stopRecording();
}
}
private void onPlay(boolean start) {
if (start) {
startPlaying();
} else {
stopPlaying();
}
}
private void startPlaying() {
mPlayer = new MediaPlayer();
try {
mPlayer.setDataSource(mFileName);
mPlayer.prepare();
mPlayer.start();
} catch (IOException e) {
Log.e(LOG_TAG, "prepare() failed");
}
}
private void stopPlaying() {
mPlayer.release();
mPlayer = null;
}
private void startRecording() {
mRecorder = new MediaRecorder();
mRecorder.setAudioSource(MediaRecorder.AudioSource.MIC);
mRecorder.setOutputFormat(MediaRecorder.OutputFormat.THREE_GPP);
mRecorder.setOutputFile(mFileName);
mRecorder.setAudioEncoder(MediaRecorder.AudioEncoder.AMR_NB);
try {
mRecorder.prepare();
} catch (IOException e) {
Log.e(LOG_TAG, "prepare() failed");
}
mRecorder.start();
}
private void stopRecording() {
mRecorder.stop();
mRecorder.release();
mRecorder = null;
}
class RecordButton extends Button {
boolean mStartRecording = true;
OnClickListener clicker = new OnClickListener() {
public void onClick(View v) {
onRecord(mStartRecording);
if (mStartRecording) {
setText("Stop recording");
} else {
setText("Start recording");
}
mStartRecording = !mStartRecording;
}
};
public RecordButton(Context ctx) {
super(ctx);
setText("Start recording");
setOnClickListener(clicker);
}
}
class PlayButton extends Button {
boolean mStartPlaying = true;
OnClickListener clicker = new OnClickListener() {
public void onClick(View v) {
onPlay(mStartPlaying);
if (mStartPlaying) {
setText("Stop playing");
} else {
setText("Start playing");
}
mStartPlaying = !mStartPlaying;
}
};
public PlayButton(Context ctx) {
super(ctx);
setText("Start playing");
setOnClickListener(clicker);
}
}
public AudioRecordTest() {
mFileName = Environment.getExternalStorageDirectory().getAbsolutePath();
mFileName += "/audiorecordtest.3gp";
}
#Override
public void onCreate(Bundle icicle) {
super.onCreate(icicle);
LinearLayout ll = new LinearLayout(this);
mRecordButton = new RecordButton(this);
ll.addView(mRecordButton,
new LinearLayout.LayoutParams(
ViewGroup.LayoutParams.WRAP_CONTENT,
ViewGroup.LayoutParams.WRAP_CONTENT,
0));
mPlayButton = new PlayButton(this);
ll.addView(mPlayButton,
new LinearLayout.LayoutParams(
ViewGroup.LayoutParams.WRAP_CONTENT,
ViewGroup.LayoutParams.WRAP_CONTENT,
0));
setContentView(ll);
}
#Override
public void onPause() {
super.onPause();
if (mRecorder != null) {
mRecorder.release();
mRecorder = null;
}
if (mPlayer != null) {
mPlayer.release();
mPlayer = null;
}
}
}
SOURCE
Offical Example link from Google
https://developer.android.com/guide/topics/media/mediarecorder.html#example
I suggest to only follow that one since its guaranteed to be up-to-date and secure.
Get manifests permission
<uses-permission android:name="android.permission.MANAGE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.RECORD_AUDIO" />
MainActivity code
AudioRecorder audioRecorder = new AudioRecorder("Service/Record");
try {
audioRecorder.start();
Toast.makeText(this, "Start", Toast.LENGTH_SHORT).show();
} catch (IOException e) {
e.printStackTrace();
Log.i("RecordError", e.getMessage());
}
findViewById(R.id.stopButton).setOnClickListener(v -> {
try {
audioRecorder.stop();
Toast.makeText(this, "Stopped", Toast.LENGTH_SHORT).show();
} catch (IOException e) {
e.printStackTrace();
}
});
AudioRecorder class code here:
public class AudioRecorder {
final MediaRecorder recorder = new MediaRecorder();
public final String path;
public AudioRecorder(String path) {
this.path = sanitizePath(path);
}
private String sanitizePath(String path) {
if (!path.startsWith("/")) {
path = "/" + path;
}
if (!path.contains(".")) {
path += ".mp3";
}
return Environment.getExternalStorageDirectory().getAbsolutePath()
+ path;
}
public void start() throws IOException {
String state = android.os.Environment.getExternalStorageState();
if (!state.equals(android.os.Environment.MEDIA_MOUNTED)) {
throw new IOException("SD Card is not mounted. It is " + state
+ ".");
}
// make sure the directory we plan to store the recording in exists
File directory = new File(path).getParentFile();
if (!directory.exists() && !directory.mkdirs()) {
throw new IOException("Path to file could not be created.");
}
recorder.setAudioSource(MediaRecorder.AudioSource.MIC);
recorder.setOutputFormat(MediaRecorder.OutputFormat.THREE_GPP);
recorder.setAudioEncoder(MediaRecorder.AudioEncoder.AMR_NB);
recorder.setOutputFile(path);
recorder.prepare();
recorder.start();
}
public void stop() throws IOException {
recorder.stop();
recorder.release();
}
public void playarcoding(String path) throws IOException {
MediaPlayer mp = new MediaPlayer();
mp.setDataSource(sanitizePath(path));
mp.prepare();
mp.start();
mp.setVolume(10, 10);
}
}
*** Get the user permission when the activity will start. MANAGE_EXTERNAL_STORAGE permission and RECORD_AUDIO permission.
From the below code I can create test.pcm file but I couldn't play it in mobile or pc.
I have also tired with test.mp3, test.wav and test.raw. I got toast that player doesn't support this type of file.
does any one has idea that how can i play file which is i have recorded using AudioRecord?
Using below code I get array of short from mic and write it into SdCard.
Here is the Code:
package com.anroid.AudioProcess;
import java.io.File;
import android.app.Activity;
import android.os.Bundle;
import android.os.Environment;
import java.io.BufferedOutputStream;
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import android.media.AudioFormat;
import android.media.AudioRecord;
import android.media.MediaRecorder;
public class AudioProcess extends Activity {
/** Called when the activity is first created. */
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
// Record 20 seconds of audio.
Recorder recorderInstance = new Recorder();
Thread th = new Thread(recorderInstance);
recorderInstance.setFileName(new File(Environment.getExternalStorageDirectory().getAbsolutePath() + "/test.pcm"));
th.start();
recorderInstance.setRecording(true);
synchronized (this) {
try {
this.wait(20000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
recorderInstance.setRecording(false);
try {
th.join();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
class Recorder implements Runnable {
private int frequency;
private int channelConfiguration;
private volatile boolean isPaused;
private File fileName;
private volatile boolean isRecording;
private final Object mutex = new Object();
// Changing the sample resolution changes sample type. byte vs. short.
private static final int audioEncoding = AudioFormat.ENCODING_PCM_16BIT;
/**
*
*/
public Recorder() {
super();
this.setFrequency(11025);
this.setChannelConfiguration(AudioFormat.CHANNEL_CONFIGURATION_MONO);
this.setPaused(false);
}
public void run() {
// Wait until we're recording...
synchronized (mutex) {
while (!this.isRecording) {
try {
mutex.wait();
} catch (InterruptedException e) {
throw new IllegalStateException("Wait() interrupted!", e);
}
}
}
// Open output stream...
if (this.fileName == null) {
throw new IllegalStateException("fileName is null");
}
BufferedOutputStream bufferedStreamInstance = null;
if (fileName.exists()) {
fileName.delete();
}
try {
fileName.createNewFile();
} catch (IOException e) {
throw new IllegalStateException("Cannot create file: " + fileName.toString());
}
try {
bufferedStreamInstance = new BufferedOutputStream(
new FileOutputStream(this.fileName));
} catch (FileNotFoundException e) {
throw new IllegalStateException("Cannot Open File", e);
}
DataOutputStream dataOutputStreamInstance =
new DataOutputStream(bufferedStreamInstance);
// We're important...
android.os.Process
.setThreadPriority(android.os.Process.THREAD_PRIORITY_URGENT_AUDIO);
// Allocate Recorder and Start Recording...
int bufferRead = 0;
int bufferSize = AudioRecord.getMinBufferSize(this.getFrequency(),
this.getChannelConfiguration(), this.getAudioEncoding());
AudioRecord recordInstance = new AudioRecord(
MediaRecorder.AudioSource.MIC, this.getFrequency(), this
.getChannelConfiguration(), this.getAudioEncoding(),
bufferSize);
short[] tempBuffer = new short[bufferSize];
recordInstance.startRecording();
while (this.isRecording) {
// Are we paused?
synchronized (mutex) {
if (this.isPaused) {
try {
mutex.wait(250);
} catch (InterruptedException e) {
throw new IllegalStateException("Wait() interrupted!",
e);
}
continue;
}
}
bufferRead = recordInstance.read(tempBuffer, 0, bufferSize);
if (bufferRead == AudioRecord.ERROR_INVALID_OPERATION) {
throw new IllegalStateException(
"read() returned AudioRecord.ERROR_INVALID_OPERATION");
} else if (bufferRead == AudioRecord.ERROR_BAD_VALUE) {
throw new IllegalStateException(
"read() returned AudioRecord.ERROR_BAD_VALUE");
} else if (bufferRead == AudioRecord.ERROR_INVALID_OPERATION) {
throw new IllegalStateException(
"read() returned AudioRecord.ERROR_INVALID_OPERATION");
}
try {
for (int idxBuffer = 0; idxBuffer < bufferRead; ++idxBuffer) {
dataOutputStreamInstance.writeShort(tempBuffer[idxBuffer]);
}
} catch (IOException e) {
throw new IllegalStateException(
"dataOutputStreamInstance.writeShort(curVal)");
}
}
// Close resources...
recordInstance.stop();
try {
bufferedStreamInstance.close();
} catch (IOException e) {
throw new IllegalStateException("Cannot close buffered writer.");
}
}
public void setFileName(File fileName) {
this.fileName = fileName;
}
public File getFileName() {
return fileName;
}
/**
* #param isRecording
* the isRecording to set
*/
public void setRecording(boolean isRecording) {
synchronized (mutex) {
this.isRecording = isRecording;
if (this.isRecording) {
mutex.notify();
}
}
}
/**
* #return the isRecording
*/
public boolean isRecording() {
synchronized (mutex) {
return isRecording;
}
}
/**
* #param frequency
* the frequency to set
*/
public void setFrequency(int frequency) {
this.frequency = frequency;
}
/**
* #return the frequency
*/
public int getFrequency() {
return frequency;
}
/**
* #param channelConfiguration
* the channelConfiguration to set
*/
public void setChannelConfiguration(int channelConfiguration) {
this.channelConfiguration = channelConfiguration;
}
/**
* #return the channelConfiguration
*/
public int getChannelConfiguration() {
return channelConfiguration;
}
/**
* #return the audioEncoding
*/
public int getAudioEncoding() {
return audioEncoding;
}
/**
* #param isPaused
* the isPaused to set
*/
public void setPaused(boolean isPaused) {
synchronized (mutex) {
this.isPaused = isPaused;
}
}
/**
* #return the isPaused
*/
public boolean isPaused() {
synchronized (mutex) {
return isPaused;
}
}
}
MediaRecorder is your need here. If you do not plan to fiddle around with raw audio data, use a MediaRecorder object to do the recording. Set the output format to THREE_GPP and it should work for you.
Changing the file extension does not change the file format, so putting .mp3, for example, does not automatically create an MP3 file. AudioRecord produces raw PCM data.
You will have to tell the media player to play a raw file, and what kind of data to expect (sample rate, encoding etc) just as you did when making the recording, since this information is not given by the file itself.
You can read instructions for doing this in Audacity here: http://delog.wordpress.com/2011/03/25/playing-raw-pcm-audio-using-audacity/
Think you should use another class then AudioRecord.
AudioRecord is raw digital impressions of what is on your soundport right now.
And what you have "borrowed" up there for an code, is just a series of numbers.
Try AudioManager instead, think thats more your style.