Hi i am trying to make a video recorder android app> For some reason i need to get its audio, i have tried some libraries but nothing really extracted me the audio. So now my approach is that instead of using native libraries can i record video and audio separately? Main thread records video and another thread records audio. I am getting error when i call start() method of media recorder class inside thread and i get Start Failed -22. Following is my code.
public class MainActivity extends Activity {
private SurfaceHolder surfaceHolder;
private SurfaceView surfaceView;
public MediaRecorder mrec ;
ImageView recordingBt;
public MediaRecorder mrec2 = new MediaRecorder();
File video;
private Camera mCamera;
File audiofile = null;
File audiofile2 = null;
boolean recording=false;
TextView tv;
View myview;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
recordingBt= (ImageView) findViewById(R.id.camera);
surfaceView = (SurfaceView) findViewById(R.id.surface_camera);
tv=(TextView) findViewById(R.id.textView1);
myview = findViewById(R.id.MyBigView);
}
#Override
protected void onStart(){
super.onStart();
Log.i("Recording Activity", "we are inside Start function of Recording Activity");
Log.i("Recording Activity", "Opening camera");
mCamera = Camera.open();
Log.i("Recording Activity", "Camera Opened");
surfaceHolder = surfaceView.getHolder();
surfaceHolder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS);
recordingBt.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if(recording==false){
try {
Log.i("Recording Activity", "Recording Start");
startRecording();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
else{
stopRecording();
}
}
});}
public void startRecording() throws IOException
{
recording=true;
String path= Environment.getExternalStorageDirectory().toString();
File sampleDir = new File(path+"/DCIM/Squlium Booth");
sampleDir.mkdir();
Log.i("Setting Path", sampleDir.toString());
try {
audiofile = File.createTempFile("SqB", ".3gp", sampleDir);
} catch (IOException e) {
return;}
Log.i("Recording Activity", "Seting Media Recorder attributes");
mrec = new MediaRecorder(); // Works well
mCamera.unlock();
mrec.setCamera(mCamera);
mrec.setPreviewDisplay(surfaceHolder.getSurface());
mrec.setVideoSource(MediaRecorder.VideoSource.CAMERA);
mrec.setAudioSource(MediaRecorder.AudioSource.MIC);
mrec.setMaxDuration(60000);
mrec.setProfile(CamcorderProfile.get(CamcorderProfile.QUALITY_HIGH));
mrec.setOutputFile(audiofile.getAbsolutePath());
mrec.prepare();
mrec.start();
startProgress(myview);
}
protected void stopRecording() {
recording=false;
mrec.stop();
mrec.release();
mCamera.lock();
mCamera.release();
mrec2.stop();
mrec.release();
}
public void startProgress(View view) {
// Do something long
Runnable runnable = new Runnable() {
#Override
public void run() {
String path= Environment.getExternalStorageDirectory().toString();
File sampleDir = new File(path+"/DCIM/Squlium Booth");
sampleDir.mkdir();
try {
audiofile2 = File.createTempFile("myAudio", ".mp3", sampleDir);
} catch (IOException e) {
return;}
int minBufferSize = AudioRecord.getMinBufferSize(8000,
AudioFormat .CHANNEL_IN_MONO,
AudioFormat.ENCODING_PCM_16BIT);
mrec2.setAudioSource(MediaRecorder.AudioSource.MIC);
mrec2.setAudioSamplingRate(16000);
mrec2.setOutputFormat(MediaRecorder.OutputFormat.AMR_NB);
mrec2.setAudioEncoder(MediaRecorder.AudioEncoder.AMR_NB);
mrec2.setOutputFile(audiofile2.getAbsolutePath());
try {
mrec2.prepare();
} catch (IllegalStateException e1) {
Log.i("Illegal", "Exception");
e1.printStackTrace();
} catch (IOException e1) {
Log.i("Iinput output", "Exception");
}
Log.i("Inside Run Method", "Starting Thread soon there will be issue");
mrec2.start();
Log.i("Inside Run Method", "After start method inside thread");
Log.i("Inside Thread", "Alive");
}
};
new Thread(runnable).start();
}
Related
I need to implement video streaming via sockets in that I have to Record video on server side and Stream it live on client side, I have connected peers via socket successfully but video stream making trouble, I am facing following problems:
I have tested Media Recorder on API level 15 and 18 but not working on higher Android version, it's giving IllegalStateException start failed -38.
Media Player is not working, I have tried ParcelFileDescriptor to get the stream from socket and also tried to save the stream into a file to play on Media Player but I gained no outcome.
public class MainActivity2 extends Activity implements SurfaceHolder.Callback{
private Handler handler = new Handler();
private TextView text;
private EditText input, serverIP, port;
private Button send, connect;
private Socket socket;
private DataOutputStream outputStream;
private BufferedReader inputStream;
private String DeviceName = "Device", ipAddr;
Thread thread;
Integer portno;
private Handler handler2 = new Handler();
MediaPlayer mp;
private SurfaceView mPreview;
private SurfaceHolder holder;
VideoView mView;
SurfaceHolder mHolder;
// Video variable
MediaRecorder recorder, mMediaRecorder;
private Handler handler3 = new Handler();
boolean isRecording = false;
String AudioSavePathInDevice = null;
ParcelFileDescriptor pfd1;
Camera mCamera;
LocalServerSocket server;
LocalSocket sender;
private boolean searchNetwork() {
log("Connecting");
String ip = serverIP.getText().toString();
portno = Integer.parseInt(port.getText().toString());
try {
socket = new Socket();
socket.connect(new InetSocketAddress(ip, portno), 100);
outputStream = new DataOutputStream(socket.getOutputStream());
inputStream = new BufferedReader(new InputStreamReader(
socket.getInputStream()));
DeviceName += "1";
Log.i("Server", DeviceName);
log("Connected");
return true;
} catch (Exception e) {
}
return false;
}
private void runNewChatServer() {
ServerSocket serverSocket;
try {
WifiManager wm = (WifiManager) getSystemService(WIFI_SERVICE);
String myIP = Formatter.formatIpAddress(wm.getConnectionInfo().getIpAddress());
serverSocket = new ServerSocket(portno);
log("I am ready to connect. Please enter the IP " + myIP + " in another device to connect...");
socket = serverSocket.accept();
DeviceName += "2";
log("another device Connected");
pfd1 = ParcelFileDescriptor.fromSocket(socket);
handler3.post(new Runnable() {
#Override
public void run() {
if (isRecording) {
// stop recording and release camera
mMediaRecorder.stop(); // stop the recording
releaseMediaRecorder(); // release the MediaRecorder object
mCamera.lock(); // take camera access back from MediaRecorder
// inform the user that recording has stopped
log("Stopped");
isRecording = false;
} else {
// initialize video camera
if (prepareVideoRecorder()) {
// Camera is available and unlocked, MediaRecorder is prepared,
// now you can start recording
try {
mMediaRecorder.start();
// inform the user that recording has started
log("Started");
isRecording = true;
} catch (IllegalStateException e) {
log("IllegalStateException in media start " + e.getStackTrace());
e.printStackTrace();
} catch (NullPointerException e) {
log("NullException in media start " + e.getMessage());
e.printStackTrace();
} catch (Exception e) {
log("Exception in media start " + e.getMessage());
e.printStackTrace();
}
} else {
// prepare didn't work, release the camera
releaseMediaRecorder();
// inform user
}
}
}
});
}
catch (Exception e) {
final String msg = e.getMessage();
log("Oops.Connection interrupted. Please reconnect your phones." + msg);
e.printStackTrace();
}
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
text = (TextView) findViewById(R.id.textin);
input = (EditText) findViewById(R.id.textout);
send = (Button) findViewById(R.id.send);
connect = (Button) findViewById(R.id.connect);
serverIP = (EditText)findViewById(R.id.serverip);
port = (EditText)findViewById(R.id.port);
mPreview = (SurfaceView) findViewById(R.id.surfaceView1);
holder = mPreview.getHolder();
holder.addCallback(this);
holder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS);
mp = new MediaPlayer();
mView = (VideoView) findViewById(R.id.videoView);
mHolder = mView.getHolder();
mHolder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS);
thread = new Thread(new Runnable() {
#Override
public void run() {
try {
if (!searchNetwork()) {
runNewChatServer();
}
else
{
prepareMediaPlayer();
}
outputStream = new DataOutputStream(
socket.getOutputStream());
inputStream = new BufferedReader(new InputStreamReader(
socket.getInputStream()));
while (true) {
String Message = inputStream.readLine();
if (Message != null) {
log(Message);
}
}
} catch (IOException e) {
log("Error: IO Exception");
e.printStackTrace();
}
catch (Exception e) {
log("Error: Exception");
e.printStackTrace();
}
}
});
send.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
if (outputStream == null) {
return;
}
try {
String Message = input.getText().toString() + "\n";
outputStream.write(Message.getBytes());
log2(input.getText().toString());
} catch (IOException e) {
e.printStackTrace();
}
input.setText("");
}
});
connect.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
ipAddr = serverIP.getText().toString();
thread.start();
}
});
}
private void log(final String message) {
handler.post(new Runnable() {
String DeviceName2 = "";
#Override
public void run() {
if (DeviceName.equals("Device1")) {
DeviceName2 = "Device2";
} else if (DeviceName.equals("Device2")) {
DeviceName2 = "Device1";
} else {
DeviceName2 = "UnknowDevice";
}
text.setText(text.getText() + "\n" + DeviceName2 + " :"
+ message);
}
});
}
private void log2(final String message) {
handler.post(new Runnable() {
#Override
public void run() {
text.setText(text.getText() + "\n" + "you" + " :"
+ message);
}
});
}
#Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
if (keyCode == KeyEvent.KEYCODE_BACK) {
if (socket != null) {
try {
socket.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
System.exit(0);
return true;
}
return super.onKeyDown(keyCode, event);
}
private boolean prepareVideoRecorder(){
mMediaRecorder = new MediaRecorder();
mCamera = getCameraInstance();
// Step 1: Unlock and set camera to MediaRecorder
mCamera.unlock();
mMediaRecorder.setCamera(mCamera);
// Step 2: Set sources
mMediaRecorder.setAudioSource(MediaRecorder.AudioSource.CAMCORDER);
mMediaRecorder.setVideoSource(MediaRecorder.VideoSource.CAMERA);
// Step 3: Set a CamcorderProfile (requires API Level 8 or higher)
mMediaRecorder.setProfile(CamcorderProfile.get(CamcorderProfile.QUALITY_LOW));
mMediaRecorder.setOutputFile(pfd1.getFileDescriptor());
// Step 5: Set the preview output
mMediaRecorder.setPreviewDisplay(mPreview.getHolder().getSurface());
// Step 6: Prepare configured MediaRecorder
try {
mMediaRecorder.prepare();
} catch (IllegalStateException e) {
log("IllegalStateException preparing MediaRecorder: " + e.getMessage());
releaseMediaRecorder();
return false;
} catch (IOException e) {
log("IOException preparing MediaRecorder: " + e.getMessage());
releaseMediaRecorder();
return false;
}
return true;
}
private boolean prepareMediaPlayer() {
try {
ParcelFileDescriptor pfd = ParcelFileDescriptor.fromSocket(socket);
pfd.getFileDescriptor().sync();
mp.setDataSource(pfd.getFileDescriptor());
pfd.close();
mp.setDisplay(mHolder);
mp.prepareAsync();
mp.start();
return true;
}catch(Exception ex){
ex.printStackTrace();
return false;
}
}
/** A safe way to get an instance of the Camera object. */
public static Camera getCameraInstance(){
Camera c = null;
try {
c = Camera.open(); // attempt to get a Camera instance
}
catch (Exception e){
Log.d("CameraInstance", e.getMessage());
// Camera is not available (in use or does not exist)
}
return c; // returns null if camera is unavailable
}
#Override
protected void onPause() {
super.onPause();
releaseMediaRecorder(); // if you are using MediaRecorder, release it first
releaseCamera(); // release the camera immediately on pause event
}
private void releaseMediaRecorder(){
if (mMediaRecorder != null) {
mMediaRecorder.reset(); // clear recorder configuration
mMediaRecorder.release(); // release the recorder object
mMediaRecorder = null;
mCamera.lock(); // lock camera for later use
}
}
private void releaseCamera(){
if (mCamera != null){
mCamera.release(); // release the camera for other applications
mCamera = null;
}
}
public void surfaceCreated(SurfaceHolder holder) {
/* try {
prepareVideoRecorder();
} catch (IllegalStateException e) {
e.printStackTrace();
log("IllegalStateException preparing MediaRecorder2: " + e.getMessage());
finish();
}*/
}
public void surfaceChanged(SurfaceHolder holder, int format, int width,
int height) {
}
public void surfaceDestroyed(SurfaceHolder holder) {
if (isRecording) {
mMediaRecorder.stop();
isRecording = false;
}
releaseMediaRecorder();
releaseCamera();
finish();
}
}
I have also used these following code snippet to save the input stream into a file to play on Media Player but it didn't work for me.
File downloadingMediaFile = File.createTempFile("downloading", ".mp4");
FileOutputStream out = new FileOutputStream(downloadingMediaFile);
IOUtils.copy(socket.getInputStream(), out);
mp.setDataSource(out.getFD());
I have tried this code snippet to Record the video stream on Lollipop or Higher API version but it's too didn't work.
ParcelFileDescriptor[] parcelFileDescriptors = new ParcelFileDescriptor[0];
try {
parcelFileDescriptors = ParcelFileDescriptor.createPipe();
} catch (IOException e) {
e.printStackTrace();
}
ParcelFileDescriptor parcelRead = new
ParcelFileDescriptor(parcelFileDescriptors[0]);
ParcelFileDescriptor parcelWrite = new
ParcelFileDescriptor(parcelFileDescriptors[1]);
mMediarecorder.setOutputFile(parcelWrite.fromSocket(socket).getFileDescriptor());
I am using media recorder to record video with following code. Can any one explain why HwMemBitMask::~HwMemBitMask ************** FORCE FREEING!!!!! message is for ? It happens when method startRecording() code get executed.
public class VideoRecorder extends FragmentActivity implements SurfaceHolder.Callback
{
MediaRecorder recorder;
SurfaceHolder holder;
boolean recording = false;
SurfaceView cameraView;
private Camera mCamera;
String filePath;
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
recorder = new MediaRecorder();
filePath = getIntent().getStringExtra("filepath");
initRecorder();
setContentView(R.layout.videorecorder);
cameraView = (SurfaceView) findViewById(R.id.video_surface_view);
holder = cameraView.getHolder();
holder.addCallback(this);
cameraView.setClickable(true);
}
private void initRecorder()
{
recorder.setAudioSource(MediaRecorder.AudioSource.DEFAULT);
recorder.setVideoSource(MediaRecorder.VideoSource.DEFAULT);
CamcorderProfile cpHigh = CamcorderProfile.get(CamcorderProfile.QUALITY_HIGH);
recorder.setProfile(cpHigh);
recorder.setOutputFile(filePath);
recorder.setMaxDuration(50000); // 50 seconds
recorder.setMaxFileSize(5000000); // Approximately 5 megabytes
}
private void prepareRecorder()
{
recorder.setPreviewDisplay(holder.getSurface());
try
{
recorder.prepare();
}
catch (IllegalStateException e)
{
e.printStackTrace();
finish();
}
catch (IOException e)
{
e.printStackTrace();
finish();
}
}
public void surfaceCreated(SurfaceHolder holder)
{
if(mCamera != null)
{
mCamera.release();
mCamera = null;
}
mCamera = Camera.open();
try
{
mCamera.setPreviewDisplay(holder);
}
catch (IOException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
prepareRecorder();
}
public void surfaceChanged(SurfaceHolder holder, int format, int width, int height)
{
mCamera.startPreview();
}
public void surfaceDestroyed(SurfaceHolder holder)
{
mCamera.stopPreview();
if (recording)
{
recorder.stop();
recording = false;
}
recorder.release();
finish();
}
public void recordButtonClick(View view)
{
Button recordButton = (Button)(view);
if(recordButton.getText().toString().contains("Record"))
{
// Recording started
findViewById(R.id.play_stop).setEnabled(false);
((Button)findViewById(R.id.cancel_done)).setText("Done");
findViewById(R.id.cancel_done).setEnabled(false);
startRecording();
findViewById(R.id.blink_recording_text).setVisibility(View.VISIBLE);
recordButton.setText("Stop");
}
else
{
findViewById(R.id.blink_recording_text).setVisibility(View.GONE);
stopRecording();
findViewById(R.id.play_stop).setEnabled(true);
findViewById(R.id.cancel_done).setEnabled(true);
recordButton.setText("Record");
}
}
public void playButtonClick(View v)
{
}
public void doneButtonClick(View v)
{
}
private void startRecording()
{
if (recording)
{
recorder.stop();
recording = false;
// Let's initRecorder so we can record again
initRecorder();
prepareRecorder();
}
else
{
recording = true;
recorder.start();
}
}
private void stopRecording()
{
if (recording)
{
recorder.stop();
recording = false;
}
}
}
I am developing a video player, at the moment it records the video, saves it when StopButton clicked or Maximum limit approached. then i can play it by clicking on the play button. What i want is that when it reaches it maximum limit lets say 60 seconds of video recording it can perform some action like automatically launch the activity which plays the video.
Following is my code:
public class VideoComponent extends Activity {
private SurfaceHolder surfaceHolder;
private SurfaceView surfaceView;
public MediaRecorder mrec = new MediaRecorder();
private Button startRecording = null;
private Button stopRecording = null;
private Button play = null;
int BytesPerElement = 2;
File video;
private Camera mCamera;
File audiofile = null;
boolean recording=false;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main1);
startRecording = (Button)findViewById(R.id.buttonstart);
stopRecording = (Button)findViewById(R.id.button1);
play=(Button)findViewById(R.id.play);
mCamera = Camera.open();
surfaceView = (SurfaceView) findViewById(R.id.surface_camera);
surfaceHolder = surfaceView.getHolder();
surfaceHolder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS);
startRecording.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
try {
if(recording==false)
startRecording();
} catch (IOException e) {
Log.i("test" , "Video Not starting");
}
}
});
stopRecording.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
recording=false;
stopRecording();
}
});
play.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent i= new Intent(getApplicationContext(),VideoPlayer.class);
i.putExtra("URI", audiofile.getAbsolutePath());
startActivity(i);
}
});
}
#Override
public boolean onCreateOptionsMenu(Menu menu)
{
Log.i("Test" , "Menu thing");
menu.add(0, 0, 0, "StartRecording");
menu.add(0, 1, 0, "StopRecording");
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item)
{
switch (item.getItemId())
{
case 0:
try {
Log.i("Test" , "Start Recording");
startRecording();
} catch (Exception e) {
String message = e.getMessage();
Log.i("Self", "Problem Start"+message);
mrec.release();
}
break;
case 1: //GoToAllNotes
mrec.stop();
mrec.release();
mrec = null;
break;
default:
break;
}
return super.onOptionsItemSelected(item);
}
public void startRecording() throws IOException
{
recording=true;
File sampleDir = Environment.getExternalStorageDirectory();
try {
audiofile = File.createTempFile("Video", ".3gp", sampleDir);
} catch (IOException e) {
return;}
int minBufferSize = AudioRecord.getMinBufferSize(8000,
AudioFormat .CHANNEL_IN_MONO,
AudioFormat.ENCODING_PCM_16BIT);
mrec = new MediaRecorder(); // Works well
mCamera.unlock();
mrec.setCamera(mCamera);
mrec.setPreviewDisplay(surfaceHolder.getSurface());
mrec.setVideoSource(MediaRecorder.VideoSource.CAMERA);
mrec.setAudioSource(MediaRecorder.AudioSource.MIC);
mrec.setMaxDuration(60000);
mrec.setAudioSamplingRate(16000);
mrec.setProfile(CamcorderProfile.get(CamcorderProfile.QUALITY_HIGH));
mrec.setPreviewDisplay( surfaceHolder.getSurface());
mrec.setOutputFile(audiofile.getAbsolutePath());
mrec.prepare();
mrec.start();
}
protected void stopRecording() {
mrec.stop();
mrec.release();
mCamera.lock();
mCamera.release();
Log.i("testing","going to call Destroyer");
//surfaceDestroyed(surfaceHolder);
//mCamera.stopPreview();
//finish();
}
private void releaseMediaRecorder(){
Log.i("testing","re;ease Media record");
if (mrec != null) {
mrec.reset(); // clear recorder configuration
mrec.release(); // release the recorder object
mrec = null;
mCamera.lock(); // lock camera for later use
}
}
private void releaseCamera(){
Log.i("testing","re;ease Camera");
if (mCamera != null){
mCamera.release(); // release the camera for other applications
mCamera = null;
}
}
}
The video Player class:
public class VideoPlayer extends Activity {
VideoView videoView;
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
//Create a VideoView widget in the layout file
//use setContentView method to set content of the activity to the layout file which contains videoView
this.setContentView(R.layout.video);
Intent i= getIntent();
String uri=i.getStringExtra("URI");
Log.i("test" , uri);
videoView = (VideoView)this.findViewById(R.id.videoView);
//add controls to a MediaPlayer like play, pause.
MediaController mc = new MediaController(this);
videoView.setMediaController(mc);
//Set the path of Video or URI
videoView.setVideoURI(Uri.parse(uri));
//Set the focus
videoView.requestFocus();
videoView.start(); } }
Consider using a CountDownTimer() ...
new CountDownTimer(1000, 1000) {
public void onTick(long millisUntilFinished) {
mTextField.setText("seconds remaining: " + millisUntilFinished / 1000);
}
public void onFinish() {
mTextField.setText("done!");
}
}.start();
http://developer.android.com/reference/android/os/CountDownTimer.html
public class FulfillVideoTaskActivity extends Activity implements SurfaceHolder.Callback, OnInfoListener, OnErrorListener{
private Button initBtn = null;
private Button startBtn = null;
private Button stopBtn = null;
private Button playBtn = null;
private Button stopPlayBtn = null;
// save Button should be implemented
private TextView recordingMsg = null;
private VideoView videoView = null;
private SurfaceHolder holder = null;
private Camera camera = null;
private static final String TAG ="RecordVideo";
private MediaRecorder recorder = null;
private String outputFileName;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_fulfill_video_task);
// get references to UI elements
initBtn = (Button) findViewById(R.id.initBtn);
startBtn = (Button) findViewById(R.id.startBtn);
stopBtn = (Button) findViewById(R.id.stopBtn);
playBtn = (Button) findViewById(R.id.playBtn);
stopPlayBtn = (Button) findViewById(R.id.stopPlayBtn);
recordingMsg = (TextView) findViewById(R.id.recording);
videoView = (VideoView)this.findViewById(R.id.videoView);
}
public void buttonTapped(View view) {
switch(view.getId()) {
case R.id.initBtn:
initRecorder();
break;
case R.id.startBtn:
beginRecording();
break;
case R.id.stopBtn:
stopRecording();
break;
case R.id.playBtn:
playRecording();
break;
case R.id.stopPlayBtn:
stopPlayback();
break;
}
}
private void stopPlayback() {
videoView.stopPlayback();
}
private void playRecording() {
MediaController mc = new MediaController(this);
videoView.setMediaController(mc);
videoView.setVideoPath(outputFileName);
videoView.start();
stopPlayBtn.setEnabled(true);
}
private void stopRecording() {
if(recorder != null) {
recorder.setOnErrorListener(null);
recorder.setOnInfoListener(null);
try {
recorder.stop();
}
catch(IllegalStateException e) {
//this can happen if the recorder has already stopped.
Log.e(TAG, "Got IllegalStateException in stopRecording");
}
releaseRecorder();
recordingMsg.setText("");
releaseCamera();
startBtn.setEnabled(false);
stopBtn.setEnabled(false);
playBtn.setEnabled(true);
}
}
private void releaseCamera() {
if(camera != null) {
try {
camera.reconnect();
} catch (IOException e) {
e.printStackTrace();
}
camera.release();
camera = null;
}
}
private void releaseRecorder() {
if(recorder != null) {
recorder.release();
recorder = null;
}
}
private void beginRecording() {
recorder.setOnInfoListener(this);
recorder.setOnErrorListener(this);
recorder.start();
recordingMsg.setText("RECORDING");
startBtn.setEnabled(false);
stopBtn.setEnabled(true);
}
// Initialize the recorder
private void initRecorder() {
if(recorder != null) return;
// The place where the video will be saved.
outputFileName = Environment.getExternalStorageDirectory() + "/videooutput.mp4";
File outFile = new File(outputFileName);
//if File already exists, we delete it
if(outFile.exists())
outFile.delete();
try{
camera.stopPreview();
camera.unlock();
recorder = new MediaRecorder();
recorder.setCamera(camera);
recorder.setAudioSource(MediaRecorder.AudioSource.CAMCORDER);
recorder.setVideoSource(MediaRecorder.VideoSource.CAMERA);
recorder.setOutputFormat(MediaRecorder.OutputFormat.MPEG_4);
recorder.setVideoSize(280, 200);
recorder.setVideoFrameRate(15);
recorder.setVideoEncoder(MediaRecorder.VideoEncoder.MPEG_4_SP);
recorder.setAudioEncoder(MediaRecorder.AudioEncoder.AMR_NB);
recorder.setMaxDuration(10000); // limit to 10 seconds
recorder.setPreviewDisplay(holder.getSurface());
recorder.setOutputFile(outputFileName); // setting our output file to our FileName
recorder.prepare();
Log.v(TAG, "MediaRecorder initialized");
initBtn.setEnabled(false);
startBtn.setEnabled(true);
}
//error checking
catch(Exception e) {
Log.v(TAG, "MediaRecorder failed to initialize");
e.printStackTrace();
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.activity_fulfill_video_task, menu);
return true;
}
public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) {
// TODO Auto-generated method stub
}
public void surfaceCreated(SurfaceHolder holder) {
Log.v(TAG, "in sufaceCreated");
try {
camera.setPreviewDisplay(holder);
camera.startPreview();
}catch (IOException e) {
Log.v(TAG, "Could not start the preview");
e.printStackTrace();
}
initBtn.setEnabled(true);
}
public void surfaceDestroyed(SurfaceHolder holder) {
// TODO Auto-generated method stub
}
public void onError(MediaRecorder mr, int what, int extra) {
Log.e(TAG, "got a recording error");
stopRecording();
Toast.makeText(this, "Recording error has occurred. Stopping the recording", Toast.LENGTH_SHORT).show();
}
public void onInfo(MediaRecorder mr, int what, int extra) {
Log.i(TAG, "got a recording event");
if(what == MediaRecorder.MEDIA_RECORDER_INFO_MAX_DURATION_REACHED) {
Log.i(TAG, "...max duration reached");
stopRecording();
Toast.makeText(this, "Recording limit has been reached. Stopping the recording", Toast.LENGTH_SHORT).show();
}
}
// disable the buttons until the camera is initialized
protected void onResume() {
Log.v(TAG, "in onResume");
super.onResume();
initBtn.setEnabled(false);
startBtn.setEnabled(false);
stopBtn.setEnabled(false);
playBtn.setEnabled(false);
stopPlayBtn.setEnabled(false);
if(!initCamera())
finish();
}
// initializes the camera
private boolean initCamera() {
try {
camera = Camera.open();
Camera.Parameters camParams = camera.getParameters();
camera.lock();
holder = videoView.getHolder();
holder.addCallback(this);
holder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS);
}
catch(RuntimeException re) {
Log.v(TAG, "Could not initialize the Camera");
re.printStackTrace();
return false;
}
return true;
}
}
Hi, I'm trying to record a video on android right now, when I run my code (the whole code above), the camera can't be initialized. I guess I have an error in the following part.
private boolean initCamera() {
try {
camera = Camera.open();
Camera.Parameters camParams = camera.getParameters();
camera.lock();
holder = videoView.getHolder();
holder.addCallback(this);
holder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS);
}
catch(RuntimeException re) {
Log.v(TAG, "Could not initialize the Camera");
re.printStackTrace();
return false;
}
return true;
}
holder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS); this line in this code gets multiple markers, saying
The method setType(int) from the type SurfaceHolder is deprecated
The field SURFACE_TYPE_PUSH_BUFFERS is deprecated
Does anyone know the reason why I'm getting this?
Try this code
first
setRecorder() ;
SurfaceView videoShootSurfaceView = (SurfaceView) findViewById(R.id.shootVideosurfaceView_VSD);
SurfaceHolder videoSurfaceHolder = videoShootSurfaceView.getHolder();
videoSurfaceHolder.addCallback(this);
videoSurfaceHolder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS);
set the recorder type
public void setRecorder() {
recorder = new MediaRecorder();
recorder.setAudioSource(MediaRecorder.AudioSource.MIC);
recorder.setVideoSource(MediaRecorder.VideoSource.CAMERA);
recorder.setOutputFormat(MediaRecorder.OutputFormat.MPEG_4);
recorder.setAudioEncoder(MediaRecorder.AudioEncoder.AMR_NB);
recorder.setVideoEncoder(MediaRecorder.VideoEncoder.MPEG_4_SP);
// recorder.setVideoSize(640, 480);
recorder.setVideoSize(320, 240);
// recorder.setVideoSize(480, 320);
// recorder.setVideoSize(176, 144);
recorder.setVideoFrameRate(15);
// recorder.setMaxDuration(3600000);
recorder.setMaxDuration(300000);
recorder.setOutputFile("/sdcard/videocapture_example.mp4");
}
override this methhod.
#Override
public void surfaceCreated(SurfaceHolder holder) {
camera = Camera.open();
recorder.setPreviewDisplay(holder.getSurface());
if (recorder != null) {
try {
recorder.prepare();
} catch (IllegalStateException e) {
Log.e("IllegalStateException", e.toString());
} catch (IOException e) {
Log.e("IOException", e.toString());
}
}
}
To start the recording
public void startRecording() {
setRecorder();
recorder.setPreviewDisplay(recoderTempHolder.getSurface());
if (recorder != null) {
try {
recorder.prepare();
recorder.start();
} catch (IllegalStateException e) {
Log.e("IllegalStateException", e.toString());
} catch (IOException e) {
Log.e("IOException", e.toString());
}
}
}
To stop the recording
public void stopRecording() {
recorder.stop();
// recorder.reset();
recorder.release();
}
is there anyway I can send an email when I press the save button with OUTPUT_FILE path from sdcard. (I didn't implement the save button yet)
Should I change String to Uri instead to send an email?
I don't know how I should implement the save button making it to send an email with the audio file attached. Any suggestions? Thanks in advance!
public class FulfillAudioTaskActivity extends Activity {
private MediaPlayer mediaPlayer;
private MediaRecorder recorder;
private String OUTPUT_FILE;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_fulfill_audio_task);
OUTPUT_FILE = Environment.getExternalStorageDirectory()+"/audiorecorder.3gpp";
}
public void buttonTapped(View view){
switch(view.getId()) {
case R.id.startBtn:
try {
beginRecording();
}catch (Exception e){
e.printStackTrace();
}
break;
case R.id.finishBtn:
try {
stopRecording();
} catch (Exception e){
e.printStackTrace();
}
break;
case R.id.playBtn:
try {
playRecording();
} catch (Exception e){
e.printStackTrace();
}
break;
case R.id.stopBtn:
try {
stopPlayback();
} catch (Exception e){
e.printStackTrace();
}
break;
}
}
private void stopPlayback() {
if(mediaPlayer != null)
mediaPlayer.stop();
}
private void playRecording() throws Exception{
ditchMediaPlayer();
mediaPlayer = new MediaPlayer();
mediaPlayer.setDataSource(OUTPUT_FILE);
mediaPlayer.prepare();
mediaPlayer.start();
}
private void ditchMediaPlayer() {
if(mediaPlayer != null)
{
try {
mediaPlayer.release();
}catch(Exception e){
e.printStackTrace();
}
}
}
// stop recording if there's a recorder running
private void stopRecording() {
if (recorder != null)
recorder.stop();
}
private void beginRecording() throws Exception {
ditchMediaRecorder();
File outFile = new File(OUTPUT_FILE);
//check if there's a file already recorded, and if it is we want to get rid of it.
if(outFile.exists())
outFile.delete();
//create a new MediaRecorder object.
recorder = new MediaRecorder();
recorder.setAudioSource(MediaRecorder.AudioSource.MIC);
recorder.setOutputFormat(MediaRecorder.OutputFormat.THREE_GPP);
recorder.setAudioEncoder(MediaRecorder.AudioEncoder.AMR_WB);
recorder.setOutputFile(OUTPUT_FILE);
recorder.prepare();
recorder.start();
}
private void ditchMediaRecorder() {
// TODO Auto-generated method stub
if(recorder != null)
recorder.release();
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.activity_fulfill_audio_task, menu);
return true;
}
}
Intent i = new Intent(Intent.ACTION_SEND);
i.setType("audio/rfc822");
i.putExtra(Intent.EXTRA_EMAIL, new String[] {"someone#gmail.com"} );
i.putExtra(Intent.EXTRA_SUBJECT, "MySubject");
i.putExtra(Intent.EXTRA_STREAM, Uri.parse(Environment.getExternalStorageDirectory().getAbsolutePath() + File.separator + "audiorecorder.3gpp");
startActivity(i);
Hope this helps!