I am new to android. I have made a simple torch light application. Everything is perfectly fine but the blinking segment is making the problem. If I presses the button "Blink", flashlight starts blinking but when I again presses the button, blinking doesn't stop rather than blinking adds up. For example if I presses the button two times then the function executes two times. If its in order then it must stop on second press. Anyone have a solution about it. please help.
Here is the MainActivity.java
package epicerastudios.torch;
import android.content.Context;
import android.content.DialogInterface;
import android.content.pm.PackageManager;
import android.hardware.camera2.CameraAccessException;
import android.hardware.camera2.CameraManager;
import android.os.Build;
import android.os.Bundle;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.View;
import android.widget.ImageButton;
public class MainActivity extends AppCompatActivity {
private CameraManager mCameraManager;
private String mCameraId;
private ImageButton mTorchOnOffButton;
private ImageButton mBlinkOnOffButton;
private Boolean isTorchOn;
private Boolean isBlinkOn;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Log.d("FlashLightActivity", "onCreate()");
setContentView(R.layout.activity_main);
mTorchOnOffButton = (ImageButton) findViewById(R.id.Switch);
mBlinkOnOffButton = (ImageButton) findViewById(R.id.Blink) ;
isTorchOn = false;
isBlinkOn = false;
Boolean isFlashAvailable = getApplicationContext().getPackageManager()
.hasSystemFeature(PackageManager.FEATURE_CAMERA_FLASH);
if (!isFlashAvailable) {
AlertDialog alert = new AlertDialog.Builder(MainActivity.this)
.create();
alert.setTitle("Error !!");
alert.setMessage("Your device doesn't support flash light!");
alert.setButton(DialogInterface.BUTTON_POSITIVE, "OK", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
// closing the application
finish();
System.exit(0);
}
});
alert.show();
return;
}
mCameraManager = (CameraManager) getSystemService(Context.CAMERA_SERVICE);
try {
mCameraId = mCameraManager.getCameraIdList()[0];
} catch (CameraAccessException e) {
e.printStackTrace();
}
mTorchOnOffButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
try {
if (isTorchOn) {
turnOffFlashLight();
isTorchOn = false;
} else {
turnOnFlashLight();
isTorchOn = true;
}
} catch (Exception e) {
e.printStackTrace();
}
}
});
mBlinkOnOffButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (isBlinkOn) {
turnOffBlink();
isBlinkOn = false;
} else {
turnOnBlink();
isBlinkOn = true;
}
}
});
}
public void turnOnFlashLight() {
try {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
mCameraManager.setTorchMode(mCameraId, true);
mTorchOnOffButton.setImageResource(R.drawable.btn_on);
}
} catch (Exception e) {
e.printStackTrace();
}
}
public void turnOffFlashLight() {
try {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
mCameraManager.setTorchMode(mCameraId, false);
mTorchOnOffButton.setImageResource(R.drawable.btn_off);
}
} catch (Exception e) {
e.printStackTrace();
}
}
public void turnOnBlink() {
mBlinkOnOffButton.setImageResource(R.drawable.blink_on);
String myString = "0101010101";
long blinkDelay = 300; //Delay in ms
for (int i = 0; i < myString.length(); i++) {
if (myString.charAt(i) == '0') {
try {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
mCameraManager.setTorchMode(mCameraId, true);
}
} catch (Exception e) {
e.printStackTrace();
}
}
else {
try {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
mCameraManager.setTorchMode(mCameraId, false);
}
}
catch (Exception e){
e.printStackTrace();
}
}
try {
Thread.sleep(blinkDelay);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
public void turnOffBlink() {
try {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
mCameraManager.setTorchMode(mCameraId, false);
mBlinkOnOffButton.setImageResource(R.drawable.blink_off);
}
} catch (Exception e) {
e.printStackTrace();
}
}
#Override
protected void onStop() {
super.onStop();
if(isTorchOn || isBlinkOn){
turnOffFlashLight();
turnOffBlink();
}
}
#Override
protected void onPause() {
super.onPause();
if(isTorchOn || isBlinkOn){
turnOffFlashLight();
turnOffBlink();
}
}
#Override
protected void onResume() {
super.onResume();
if(isTorchOn || isBlinkOn){
turnOnFlashLight();
turnOnBlink();
}
}
}
Here is my activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="epicerastudios.torch.MainActivity"
android:background="#fff">
<ImageButton
android:id="#+id/Switch"
android:layout_width="250dp"
android:layout_height="wrap_content"
android:background="#fff"
android:layout_centerHorizontal="true"
android:layout_centerVertical="true"
android:src="#drawable/btn_off" />
<ImageButton
android:id="#+id/Blink"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true"
android:layout_below="#id/Switch"
android:layout_alignLeft="#id/Switch"
android:background="#fff"
android:src="#drawable/blink_off" />
</RelativeLayout>
I think it's becouse of your for loop which is not stopped when you press the button again.
public void turnOnBlink() {
mBlinkOnOffButton.setImageResource(R.drawable.blink_on);
String myString = "0101010101";
long blinkDelay = 300; //Delay in ms
for (int i = 0; i < myString.length(); i++) {
if(!isBlinkOn) {
break;
}
if (myString.charAt(i) == '0') {
try {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
mCameraManager.setTorchMode(mCameraId, true);
}
} catch (Exception e) {
e.printStackTrace();
}
}
button
mBlinkOnOffButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (isBlinkOn) {
isBlinkOn = false;
turnOffBlink();
} else {
isBlinkOn = true;
turnOnBlink();
}
}
});
Related
I tried to make flashlight blink on pressing a button continuously until the button is pressed again. The flash is blinking continuously but I am unable to stop the blinking as the app freezes. Here is my Code:
public void Buts1(View view) {
CameraManager cameraManager = (CameraManager) getSystemService(Context.CAMERA_SERVICE);
long blinkDelay = 50;//delay in ms
if(textView.getText().toString().equals("ON")){
boolean s=false;
while (textView.getText().toString().equals("ON")){
if(s){
try {
String cameraId = cameraManager.getCameraIdList()[0];
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
cameraManager.setTorchMode(cameraId, true);
}
} catch (CameraAccessException e) {
}
s=false;
}else{
try {
String cameraId = cameraManager.getCameraIdList()[0];
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
cameraManager.setTorchMode(cameraId, false);
}
} catch (CameraAccessException e) {
}
s=true;
}
try {
Thread.sleep(blinkDelay);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
I believe you're freezing the UI thread here. Also I don't see anything that sets the textView text to "OFF".
I've slightly modified your code, which assumes textView starts with the text "OFF" and will change to "ON" when you click the button. Clicking the button again will set the textView text to "OFF" and turn the flashing off. This works by being on a separate thread instead of the UI thread.
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
final CameraManager cameraManager = (CameraManager) getSystemService(Context.CAMERA_SERVICE);
Thread flashThread = new Thread(new Runnable() {
#Override
public void run() {
boolean s=false;
long blinkDelay = 50;//delay in ms
while (textView.getText().toString().equals("ON")){
if(s){
try {
String cameraId = cameraManager.getCameraIdList()[0];
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
cameraManager.setTorchMode(cameraId, true);
}
} catch (CameraAccessException e) {
}
s=false;
}else{
try {
String cameraId = cameraManager.getCameraIdList()[0];
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
cameraManager.setTorchMode(cameraId, false);
}
} catch (CameraAccessException e) {
}
s=true;
}
try {
Thread.sleep(blinkDelay);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
});
if(textView.getText().toString().equalsIgnoreCase("OFF")){
textView.setText("ON");
flashThread.start();
}else{
flashThread.interrupt();
try {
String cameraId = cameraManager.getCameraIdList()[0];
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
cameraManager.setTorchMode(cameraId, false);
}
} catch (CameraAccessException e) {
}
textView.setText("OFF");
}
}
});
this thread automatically stops the media Recorder after 15 seconds.. I want to stop the thread manually also before 15 seconds when I click the stop button so what to do
recordstart.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
c=1;
recordstart.setVisibility(View.GONE);
recordstop.setVisibility(View.VISIBLE);
recordcomplete.setVisibility(View.GONE);
if(checkPermission()) {
AudioSavePathInDevice =
Environment.getExternalStorageDirectory().getAbsolutePath() + "/" +
CreateRandomAudioFileName(5) + "AudioRecording.3gp";
MediaRecorderReady();
try {
//mediaRecorder.setMaxDuration(15000);
mediaRecorder.prepare();
mediaRecorder.start();
if (view.getId() == R.id.record) {
new Timer().schedule(new TimerTask() {
#Override
public void run() {
runOnUiThread(new Runnable() {
#Override
public void run()
{
mediaRecorder.stop();
recordstart.setVisibility(View.GONE);
recordstop.setVisibility(View.GONE);
recordcomplete.setVisibility(View.VISIBLE);
Toast.makeText(UploadActivity.this, "Recording Completed",
Toast.LENGTH_LONG).show();
}
});
}
}, 15000);
}
} catch (IllegalStateException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
Toast.makeText(UploadActivity.this, "Recording started",
Toast.LENGTH_LONG).show();
} else {
requestPermission();
}
}
});
recordstop.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
mediaRecorder.stop();
recordstart.setVisibility(View.GONE);
recordstop.setVisibility(View.GONE);
recordcomplete.setVisibility(View.VISIBLE);
Toast.makeText(UploadActivity.this, "Recording Completed",
Toast.LENGTH_LONG).show();
}
});
this is whole code
package com.dell.mubox;
ImageView recordstart, play, upload, recordstop, recordcomplete;
String AudioSavePathInDevice = null;
MediaRecorder mediaRecorder ;
Random random ;
String RandomAudioFileName = "ABCDEFGHIJKLMNOP";
public static final int RequestPermissionCode = 1;
MediaPlayer mediaPlayer ;
int c=0;
Timer t;
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_upload);
recordstart = (ImageView)findViewById(R.id.record);
recordstop = (ImageView)findViewById(R.id.recordstop);
play = (ImageView)findViewById(R.id.play);
upload = (ImageView)findViewById(R.id.upload);
recordcomplete = (ImageView)findViewById(R.id.recordcomplete);
random = new Random();
recordstart.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
c=1;
recordstart.setVisibility(View.GONE);
recordstop.setVisibility(View.VISIBLE);
recordcomplete.setVisibility(View.GONE);
if(checkPermission()) {
AudioSavePathInDevice =
Environment.getExternalStorageDirectory().getAbsolutePath() + "/" +
CreateRandomAudioFileName(5) + "AudioRecording.3gp";
MediaRecorderReady();
try {
//mediaRecorder.setMaxDuration(15000);
mediaRecorder.prepare();
mediaRecorder.start();
if (view.getId() == R.id.record) {
new Timer().schedule(new TimerTask() {
#Override
public void run() {
runOnUiThread(new Runnable() {
#Override
public void run()
{
mediaRecorder.stop();
recordstart.setVisibility(View.GONE);
recordstop.setVisibility(View.GONE);
recordcomplete.setVisibility(View.VISIBLE);
Toast.makeText(UploadActivity.this, "Recording Completed",
Toast.LENGTH_LONG).show();
}
});
}
}, 15000);
}
} catch (IllegalStateException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
Toast.makeText(UploadActivity.this, "Recording started",
Toast.LENGTH_LONG).show();
} else {
requestPermission();
}
}
});
recordstop.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
mediaRecorder.stop();
recordstart.setVisibility(View.GONE);
recordstop.setVisibility(View.GONE);
recordcomplete.setVisibility(View.VISIBLE);
Toast.makeText(UploadActivity.this, "Recording Completed",
Toast.LENGTH_LONG).show();
}
});
play.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) throws IllegalArgumentException,
SecurityException, IllegalStateException {
if (c == 1) {
recordstart.setVisibility(View.VISIBLE);
recordstop.setVisibility(View.GONE);
recordcomplete.setVisibility(View.GONE);
mediaPlayer = new MediaPlayer();
try {
c = 0;
mediaPlayer.setDataSource(AudioSavePathInDevice);
mediaPlayer.prepare();
} catch (IOException e) {
e.printStackTrace();
}
try {
mediaPlayer.start();
} catch (Exception e) {
Toast.makeText(UploadActivity.this, "No Audio Found", Toast.LENGTH_LONG).show();
}
Toast.makeText(UploadActivity.this, "Recording Playing",
Toast.LENGTH_LONG).show();
} else {
Toast.makeText(UploadActivity.this, "Record Audio First", Toast.LENGTH_LONG).show();
}
}
});
upload.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Toast.makeText(UploadActivity.this, "Audio Uploaded Successfully", Toast.LENGTH_LONG).show();
}
});
/* buttonStopPlayingRecording.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
buttonStop.setEnabled(false);
buttonStart.setEnabled(true);
buttonStopPlayingRecording.setEnabled(false);
buttonPlayLastRecordAudio.setEnabled(true);
if(mediaPlayer != null){
mediaPlayer.stop();
mediaPlayer.release();
MediaRecorderReady();
}
}
});*/
}
public void MediaRecorderReady(){
mediaRecorder=new MediaRecorder();
mediaRecorder.setAudioSource(MediaRecorder.AudioSource.MIC);
mediaRecorder.setOutputFormat(MediaRecorder.OutputFormat.THREE_GPP);
mediaRecorder.setAudioEncoder(MediaRecorder.OutputFormat.AMR_NB);
mediaRecorder.setOutputFile(AudioSavePathInDevice);
}
public String CreateRandomAudioFileName(int string){
StringBuilder stringBuilder = new StringBuilder( string );
int i = 0 ;
while(i < string ) {
stringBuilder.append(RandomAudioFileName.
charAt(random.nextInt(RandomAudioFileName.length())));
i++ ;
}
return stringBuilder.toString();
}
private void requestPermission() {
ActivityCompat.requestPermissions(UploadActivity.this, new
String[]{WRITE_EXTERNAL_STORAGE, RECORD_AUDIO}, RequestPermissionCode);
}
#Override
public void onRequestPermissionsResult(int requestCode,
String permissions[], int[] grantResults) {
switch (requestCode) {
case RequestPermissionCode:
if (grantResults.length> 0) {
boolean StoragePermission = grantResults[0] ==
PackageManager.PERMISSION_GRANTED;
boolean RecordPermission = grantResults[1] ==
PackageManager.PERMISSION_GRANTED;
if (StoragePermission && RecordPermission) {
Toast.makeText(UploadActivity.this, "Permission Granted",
Toast.LENGTH_LONG).show();
} else {
Toast.makeText(UploadActivity.this,"Permission Denied",Toast.LENGTH_LONG).show();
}
}
break;
}
}
public boolean checkPermission() {
int result = ContextCompat.checkSelfPermission(getApplicationContext(),
WRITE_EXTERNAL_STORAGE);
int result1 = ContextCompat.checkSelfPermission(getApplicationContext(),
RECORD_AUDIO);
return result == PackageManager.PERMISSION_GRANTED &&
result1 == PackageManager.PERMISSION_GRANTED;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case android.R.id.home:
// app icon in action bar clicked; goto parent activity.
this.finish();
return true;
default:
return super.onOptionsItemSelected(item);
}
}
}
i want to add flashlight Blinking mode in android studio with a button. but i don't know that how can i put a code and how to implement this code with a button. because i want that if i press button then flashlight start blinking.
can anyone tell me that how can i implement this code with a button?
String[] list1 = { "1", "0", "1", "0", "1", "0", "1", "0", "1", "0" };
for (int i = 0; i < list1.length; i++) {
if (list1[i].equals("0")) {
params.setFlashMode(Parameters.FLASH_MODE_ON);
} else {
params.setFlashMode(Parameters.FLASH_MODE_OFF);
}
}
You can use this code for blink i make this as method :
private void BlinkFlash(){
String myString = "010101010101";
long blinkDelay =50; //Delay in ms
for (int i = 0; i < myString.length(); i++) {
if (myString.charAt(i) == '0') {
params = camera.getParameters();
params.setFlashMode(Camera.Parameters.FLASH_MODE_TORCH);
camera.setParameters(params);
camera.startPreview();
isFlashOn = true;
} else {
params = camera.getParameters();
params.setFlashMode(Camera.Parameters.FLASH_MODE_OFF);
camera.setParameters(params);
camera.stopPreview();
isFlashOn = false;
}
try {
Thread.sleep(blinkDelay);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
and it will call like this :
BlinkMode.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
BlinkFlash();
}
});
Hope this will work for you and yeah make string long if you want blink long time then
All of these below codes put inside any where in your activity/fragment:
Status, handler, Camera variables:
boolean isOn[] = {false};
boolean[] isBlinking = {false};
Handler handler = new Handler();
CameraManager camManager = null;
String cameraId = null;
Handle button click listener on your activity/fragment:
camManager = (CameraManager) view.getContext().getSystemService(Context.CAMERA_SERVICE);
buttonFlash.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if(!isBlinking[0]){
BlinkMode(view);
isBlinking[0] = true;
} else {
if(splashThread2 != null){
splashThread2.interrupt(); // stop blinking
OffFlash();
}
isBlinking[0] = false;
}
}
});
Blinking method:
Thread splashThread2;
private void BlinkMode(View view){
splashThread2 = new Thread() {
#Override
public void run() {
try {
while (!isInterrupted()) {
Thread.sleep(100);
if(!isOn[0]){
OnFlash();
isOn[0] = true;
} else {
isOn[0] = false;
OffFlash();
}
}
} catch (Exception e) {
}
}
};
splashThread2.start();
}
Handle when goback
#Override
public void onStop() {
super.onStop();
if(splashThread2 != null){
splashThread2.interrupt(); // stop blinking
OffFlash();
}
// todo check null exception
}
#Override
public void onPause() {
super.onPause();
if(splashThread2 != null){
splashThread2.interrupt(); // stop blinking
OffFlash();
}
// todo check null exception
}
On/Off Method for new version of Android:
private void OnFlash(){
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
try {
cameraId = camManager.getCameraIdList()[0];
camManager.setTorchMode(cameraId, true); //Turn ON
isOn[0] = true;
} catch (CameraAccessException e) {
e.printStackTrace();
}
}
}
private void OffFlash(){
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
try {
cameraId = camManager.getCameraIdList()[0];
camManager.setTorchMode(cameraId, false); //Turn ON
isOn[0] = false;
} catch (CameraAccessException e) {
e.printStackTrace();
}
}
}
I am making an application in which user can record video throuh customized camera. and User can also record a video through front camera. It is recorded fine but when we played it in normal Media player it is playing just at 180 degree. I don't know how it can be possible and how to resolve the same? Please suggest me any solution regarding the same.
Code:
package com.irantapps.cameraApplication;
import java.io.File;
import java.io.IOException;
import android.annotation.SuppressLint;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.database.Cursor;
import android.hardware.Camera;
import android.media.ExifInterface;
import android.media.MediaPlayer;
import android.media.MediaRecorder;
import android.media.MediaRecorder.VideoEncoder;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.os.SystemClock;
import android.provider.MediaStore;
import android.util.Log;
import android.view.KeyEvent;
import android.view.Surface;
import android.view.SurfaceHolder;
import android.view.SurfaceView;
import android.view.View;
import android.view.Window;
import android.view.animation.AlphaAnimation;
import android.view.animation.Animation;
import android.view.animation.LinearInterpolator;
import android.widget.Button;
import android.widget.Chronometer;
import android.widget.ImageButton;
import android.widget.LinearLayout;
import android.widget.Toast;
import com.irantapps.AfterLoginHome;
import com.irantapps.BaseActivity;
import com.irantapps.CameraPlay_New;
import com.irantapps.R;
import com.irantapps.utility.DateAndLength;
import com.irantapps.utility.VideoDetailsCollection;
/***
* TODO: 1. sound on/off 2. resolution change
*
* #author roman10
*
*/
public class VideoCapture_New extends BaseActivity implements
SurfaceHolder.Callback {
private SurfaceView prSurfaceView;
private ImageButton prStartBtn, prFrontBackCamera;
private Button prSettingsBtn;
private ImageButton btn_Gallery;
public String TAG = "IRANT";
private boolean prRecordInProcess;
private SurfaceHolder prSurfaceHolder;
private Camera prCamera;
private final String cVideoFilePath = "/sdcard/";
Chronometer cm_VideoCapture;
private Context prContext;
public static boolean frontCamera = false;
int mRotation;
LinearLayout linearLayoutRedbtn;
ImageButton btn;
Animation animation;
ImageButton btn_Cancel;
DateAndLength findDateandLength;
private VideoDetailsCollection videoDetails = VideoDetailsCollection.getSingletonObject();
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
this.requestWindowFeature(Window.FEATURE_NO_TITLE);
prContext = this.getApplicationContext();
setContentView(R.layout.videocapture_new);
Utils.createDirIfNotExist(cVideoFilePath);
findDateandLength=DateAndLength.getSingletonObject();
animation = new AlphaAnimation(1, 0); // Change alpha from fully visible
// to invisible
animation.setDuration(500); // duration - half a second
animation.setInterpolator(new LinearInterpolator()); // do not alter
// animation
// rate
animation.setRepeatCount(Animation.INFINITE); // Repeat animation
// infinitely
animation.setRepeatMode(Animation.REVERSE); // Reverse animation at the
// end so the button will
// fade back in
btn = (ImageButton) findViewById(R.id.main_btn1);
btn_Cancel = (ImageButton)findViewById(R.id.btn_wrongTick);
btn_Gallery = (ImageButton)findViewById(R.id.btn_gallerySelector);
linearLayoutRedbtn = (LinearLayout) findViewById(R.id.linear_btn1);
linearLayoutRedbtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
if (prRecordInProcess == false) {
cm_VideoCapture.setBase(SystemClock.elapsedRealtime());
//cm_VideoCapture.clearComposingText();
cm_VideoCapture.start();
try {
startRecording();
} catch (NoSuchMethodException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
linearLayoutRedbtn.startAnimation(animation);
} else {
stopRecording();
linearLayoutRedbtn.clearAnimation();
cm_VideoCapture.stop();
findDateandLength.setTimeLengthOfVideo(cm_VideoCapture.getText().toString());
//Toast.makeText(getApplicationContext(), "hello..."+cm_VideoCapture.getText(), Toast.LENGTH_LONG).show();
cm_VideoCapture.clearComposingText();
Intent intent = new Intent(VideoCapture_New.this,
CameraPlay_New.class);
startActivity(intent);
}
}
});
btn_Gallery.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
Intent intent = new Intent();
intent.setType("video/*");
intent.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(Intent.createChooser(intent,"Select Video"), 2);
}
});
cm_VideoCapture = (Chronometer) findViewById(R.id.cm_VideoCapture);
prSurfaceView = (SurfaceView) findViewById(R.id.surface_camera);
prStartBtn = (ImageButton) findViewById(R.id.main_btn1);
prFrontBackCamera = (ImageButton) findViewById(R.id.btn_frontBackCamera);
//cm_VideoCapture.start();
cm_VideoCapture.clearComposingText();
// prSettingsBtn = (Button) findViewById(R.id.main_btn2);
prRecordInProcess = false;
prStartBtn.setOnClickListener(new View.OnClickListener() {
// #Override
public void onClick(View v) {
if (prRecordInProcess == false) {
cm_VideoCapture.setBase(SystemClock.elapsedRealtime());
//cm_VideoCapture.clearComposingText();
cm_VideoCapture.start();
try {
startRecording();
} catch (NoSuchMethodException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
} else {
stopRecording();
btn.clearAnimation();
cm_VideoCapture.stop();
cm_VideoCapture.clearComposingText();
Intent intent = new Intent(VideoCapture_New.this,
CameraPlay_New.class);
startActivity(intent);
}
}
});
prFrontBackCamera.setOnClickListener(new View.OnClickListener() {
#SuppressLint("NewApi")
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
// prCamera = openFrontFacingCameraGingerbread();
try {
if (Camera.getNumberOfCameras() == 2) {
if (frontCamera) {
frontCamera = false;
prCamera.stopPreview();
prMediaRecorder.release();
prMediaRecorder = null;
prCamera.release();
prCamera = null;
} else {
frontCamera = true;
prCamera.stopPreview();
prMediaRecorder.release();
prMediaRecorder = null;
prCamera.release();
prCamera = null;
}
Intent intent = new Intent(VideoCapture_New.this,
VideoCapture_New.class);
startActivity(intent);
} else {
Toast.makeText(VideoCapture_New.this,
"Your device doesn't contain Front Camera.",
Toast.LENGTH_SHORT).show();
}
} catch (Exception e) {
e.printStackTrace();
Toast.makeText(VideoCapture_New.this,
"Your device is not compatible for Front Camera.",
Toast.LENGTH_SHORT).show();
}
}
});
prSurfaceHolder = prSurfaceView.getHolder();
prSurfaceHolder.addCallback(this);
prSurfaceHolder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS);
// prCamera.setDisplayOrientation(90);
prMediaRecorder = new MediaRecorder();
btn_Cancel.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
finish();
}
});
}
#Override
public void surfaceChanged(SurfaceHolder _holder, int _format, int _width,
int _height) {
Camera.Parameters lParam = prCamera.getParameters();
prCamera.setParameters(lParam);
try {
prCamera.setPreviewDisplay(_holder);
prCamera.startPreview();
// prPreviewRunning = true;
} catch (IOException _le) {
_le.printStackTrace();
}
}
#SuppressLint({ "NewApi", "NewApi", "NewApi", "NewApi", "NewApi", "NewApi", "NewApi", "NewApi", "NewApi", "NewApi", "NewApi", "NewApi" })
#Override
public void surfaceCreated(SurfaceHolder arg0) {
if (frontCamera == false && prCamera== null) {
/*prCamera = Camera.open();
if (prCamera == null) {
Toast.makeText(this.getApplicationContext(),
"Camera is not available!", Toast.LENGTH_SHORT).show();
finish();
}*/
prCamera = Camera.open();
try {
prCamera.setPreviewDisplay(arg0);
// TODO test how much setPreviewCallbackWithBuffer is faster
//prCamera.setPreviewCallback(VideoCapture_New.this);
} catch (IOException e) {
prCamera.release();
prCamera = null;
}
if (prCamera == null) {
Toast.makeText(this.getApplicationContext(),
"Camera is not available!", Toast.LENGTH_SHORT).show();
finish();
}
}
/*else if (prCamera == null) {
prCamera = Camera.open();
try {
prCamera.setPreviewDisplay(arg0);
// TODO test how much setPreviewCallbackWithBuffer is faster
//prCamera.setPreviewCallback(VideoCapture_New.this);
} catch (IOException e) {
prCamera.release();
prCamera = null;
}
if (prCamera == null) {
Toast.makeText(this.getApplicationContext(),
"Camera is not available!", Toast.LENGTH_SHORT).show();
finish();
}
}*/else if (prCamera!=null){
prCamera.stopPreview();
prCamera.release();
prCamera=null;
}
else if (frontCamera == true) {
try {
int cameraCount = 0;
Camera.CameraInfo cameraInfo = new Camera.CameraInfo();
cameraCount = Camera.getNumberOfCameras();
for (int camIdx = 0; camIdx < cameraCount; camIdx++) {
Camera.getCameraInfo(camIdx, cameraInfo);
if (cameraInfo.facing == Camera.CameraInfo.CAMERA_FACING_FRONT) {
try {
prCamera = Camera.open(camIdx);
} catch (RuntimeException e) {
Log.i("Camera failed to open: ",
e.getLocalizedMessage());
}
}
}
} catch (Exception e) {
Toast.makeText(VideoCapture_New.this,
"Your Device doesn't compatible for Fron Camera.",
Toast.LENGTH_SHORT).show();
}
}
try {
Camera.CameraInfo info = new android.hardware.Camera.CameraInfo();
Camera.getCameraInfo(0, info);
int rotation = getWindowManager().getDefaultDisplay().getRotation();
int degrees = 0;
switch (rotation) {
case Surface.ROTATION_0:
degrees = 0;
break;
case Surface.ROTATION_90:
degrees = 90;
break;
case Surface.ROTATION_180:
degrees = 180;
break;
case Surface.ROTATION_270:
degrees = 270;
break;
}
int result;
if (info.facing == Camera.CameraInfo.CAMERA_FACING_FRONT) {
result = (info.orientation + degrees) % 180;
result = (360 - result) % 360; // compensate the mirror
} else { // back-facing
result = (info.orientation - degrees + 360) % 360;
}
this.mRotation = result;
prCamera.setDisplayOrientation(result);
} catch (NoClassDefFoundError e) {
// TODO Auto-generated catch block
e.printStackTrace();
prCamera.setDisplayOrientation(90);
Toast.makeText(VideoCapture_New.this,
"There is no Front Camera Facility.", Toast.LENGTH_SHORT)
.show();
}
}
#Override
public void surfaceDestroyed(SurfaceHolder holder) {
if (prCamera != null) {
prCamera.stopPreview();
prCamera.setPreviewCallback(null);
prCamera.release();
prCamera = null;
}
}
/*#Override
public void surfaceDestroyed(SurfaceHolder arg0) {
try {
if (prRecordInProcess) {
stopRecording();
} else {
prCamera.stopPreview();
}
prMediaRecorder.release();
prMediaRecorder = null;
prCamera.release();
prCamera = null;
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}*/
private MediaRecorder prMediaRecorder;
private final int cMaxRecordDurationInMs = 30000;
private final long cMaxFileSizeInBytes = 5000000;
private final int cFrameRate = 20;
private File prRecordedFile;
private void updateEncodingOptions() {
if (prRecordInProcess) {
stopRecording();
try {
startRecording();
} catch (NoSuchMethodException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
Toast.makeText(prContext, "Recording restarted with new options!",
Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(prContext, "Recording options updated!",
Toast.LENGTH_SHORT).show();
}
}
#SuppressLint("NewApi")
private boolean startRecording() throws NoSuchMethodException {
prCamera.stopPreview();
try {
prCamera.unlock();
prMediaRecorder.setCamera(prCamera);
prMediaRecorder.setVideoSource(MediaRecorder.VideoSource.CAMERA);
prMediaRecorder.setAudioSource(MediaRecorder.AudioSource.DEFAULT);
String lVideoFileFullPath = ".mov";
prMediaRecorder.setOutputFormat(MediaRecorder.OutputFormat.MPEG_4);
String lDisplayMsg = "Current container format: ";
prMediaRecorder.setAudioEncoder(MediaRecorder.AudioEncoder.DEFAULT);
prMediaRecorder.setVideoEncoder(VideoEncoder.H263);
prMediaRecorder.setOrientationHint(90);
lDisplayMsg += "Current encoding format: ";
lVideoFileFullPath = Environment.getExternalStorageDirectory() + "/myvideo.mp4";
// prMediaRecorder.setOrientationHint(360);
//prMediaRecorder.setVideoSize(176, 144);
//prMediaRecorder.setVideoFrameRate(12);
prRecordedFile = new File(lVideoFileFullPath);
prMediaRecorder.setOutputFile(prRecordedFile.getPath());
//prMediaRecorder.setVideoFrameRate(cFrameRate);
prMediaRecorder.setPreviewDisplay(prSurfaceHolder.getSurface());
//prMediaRecorder.setMaxDuration(cMaxRecordDurationInMs);
//prMediaRecorder.setMaxFileSize(cMaxFileSizeInBytes);
// prepare for capturing
// state: DataSourceConfigured => prepared
prMediaRecorder.prepare();
// start recording
// state: prepared => recording
prMediaRecorder.start();
// prStartBtn.setText("Stop");
prRecordInProcess = true;
ExifInterface exif_Video = new ExifInterface(lVideoFileFullPath); //Since API Level 5
String exifOrientation_video = exif_Video.getAttribute(ExifInterface.TAG_ORIENTATION);
return true;
} catch (IOException _le) {
_le.printStackTrace();
return false;
}
}
private void stopRecording() {
prMediaRecorder.stop();
prMediaRecorder.reset();
try {
prCamera.reconnect();
} catch (IOException e) {
e.printStackTrace();
}
// prStartBtn.setText("Start");
prRecordInProcess = false;
prCamera.startPreview();
}
private static final int REQUEST_DECODING_OPTIONS = 0;
#Override
protected void onActivityResult(int requestCode, int resultCode,
Intent intent) {
super.onActivityResult(requestCode, resultCode, intent);
switch (requestCode) {
case REQUEST_DECODING_OPTIONS:
if (resultCode == RESULT_OK) {
updateEncodingOptions();
}
break;
case 2:
if (resultCode == RESULT_OK) {
//updateEncodingOptions();
if(requestCode == 2)
{
Uri selectedImageUri = intent.getData();
String selectedImagePath = getPath(selectedImageUri);
System.out.println("Image Path : " + selectedImagePath);
File file_Video = new File(selectedImagePath);
MediaPlayer mp = new MediaPlayer();
try {
mp.setDataSource(file_Video.getAbsolutePath());
videoDetails.setVideoPath(file_Video.getAbsolutePath());
if(mp.getDuration()<=3)
{
Intent intentGallery = new Intent(VideoCapture_New.this, CameraPlay_New.class);
startActivity(intentGallery);
}
else
{
AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(
this);
// set title
alertDialogBuilder
.setTitle("Info");
// set dialog message
alertDialogBuilder
.setMessage("Video can't be larger than 3 mins.")
.setCancelable(false)
.setPositiveButton("OK",new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog,int id) {
// if this button is clicked, close
// current activity
dialog.cancel();
}
});
// create alert dialog
AlertDialog alertDialog = alertDialogBuilder.create();
// show it
alertDialog.show();
}
} catch (IllegalArgumentException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IllegalStateException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.println("Video Length:"+mp.getDuration());
}
//img.setImageURI(selectedImageUri);
}
break;
}
}
public String getPath(Uri uri) {
String[] projection = { MediaStore.Video.Media.DATA };
Cursor cursor = managedQuery(uri, projection, null, null, null);
int column_index = cursor.getColumnIndexOrThrow(MediaStore.Video.Media.DATA);
cursor.moveToFirst();
return cursor.getString(column_index);
}
#Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
if (keyCode == KeyEvent.KEYCODE_BACK) {
/*
* if(collapse==true||collapse_cat==true||collapse_FuelEconomy==true||
* collapse_LatestNews
* ==true||collapse_price==true||collapse_RecentlyViwed==true){
* Intent restartResearchActivity = new
* Intent(ResearchListNew.this,ResearchListNew.class);
* restartResearchActivity.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
* startActivity(restartResearchActivity);
*
* } else { finish(); }
*/
if (prRecordInProcess == false)
{
prCamera.lock();
}
else
{
stopRecording();
prCamera.lock();
}
Intent intent = new Intent(VideoCapture_New.this,
AfterLoginHome.class);
intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(intent);
return true;
} else {
return super.onKeyDown(keyCode, event);
}
}
}
Thanks in advance.
new Camera().setDisplayOrientation(90);
I am recording audio using AudioRecord class.I want to record audio into a particular file in my asset folder or resource folder.I think there is no problem in recording.but while reading buffer it is showing some problem(it is throwing NullPointerException).Can anyone suggest what may be the problem?
You can not save file inside Asset folder. Assets folder is read only instead of it you will have to save it in the internal or external storage of your device
Below there is a core to record the media file.
package com.example.media.record;
import java.io.File;
import java.io.IOException;
import android.app.Activity;
import android.media.MediaPlayer;
import android.media.MediaPlayer.OnCompletionListener;
import android.media.MediaPlayer.OnErrorListener;
import android.media.MediaRecorder;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Handler.Callback;
import android.os.Message;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.ProgressBar;
import android.widget.Toast;
public class MediaRecorderActivity extends Activity implements OnClickListener {
Button btnPlay;
Button btnRecord;
ProgressBar progress;
MediaPlayer mPlayer;
MediaRecorder mRecorder;
String mFileName;
boolean mStartRecording = true;
boolean mStartPlaying = true;
Thread mThreadProgress;
int duration = 1;
private void onRecord(boolean start) {
if(start) {
startRecording();
}else {
stopRecording();
}
}
private void onPlay(boolean start) {
if(start) {
startPlaying();
}else {
stopPlaying();
}
}
private void startRecording() {
mRecorder = new MediaRecorder();
mRecorder.setAudioSource(MediaRecorder.AudioSource.MIC);
mRecorder.setOutputFile(mFileName);
mRecorder.setOutputFormat(MediaRecorder.OutputFormat.THREE_GPP);
mRecorder.setAudioEncoder(MediaRecorder.AudioEncoder.AMR_NB);
mRecorder.setOnErrorListener(errorListenerForRecorder);
try {
mRecorder.prepare();
} catch (IllegalStateException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
try {
mRecorder.start();
} catch (Exception e) {
Toast.makeText(getApplicationContext(), "Error :: " + e.getMessage(), Toast.LENGTH_LONG).show();
}
}
private void stopRecording() {
if(mRecorder != null) {
mRecorder.stop();
mRecorder.release();
mRecorder = null;
}
}
private void startPlaying() {
mPlayer = new MediaPlayer();
try {
mPlayer.setDataSource(mFileName);
mPlayer.setOnCompletionListener(completionListener);
mPlayer.setOnErrorListener(errorListenerForPlayer);
mPlayer.prepare();
mPlayer.start();
} catch (IllegalArgumentException e) {
e.printStackTrace();
} catch (IllegalStateException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
private void stopPlaying() {
if(mPlayer != null) {
mPlayer.stop();
mPlayer.release();
mPlayer = null;
}
}
OnCompletionListener completionListener = new OnCompletionListener() {
#Override
public void onCompletion(MediaPlayer mp) {
btnRecord.setEnabled(true);
btnPlay.setText("Start playing");
mStartPlaying = !mStartPlaying;
}
};
OnErrorListener errorListenerForPlayer = new OnErrorListener() {
#Override
public boolean onError(MediaPlayer mp, int what, int extra) {
Toast.makeText(getApplicationContext(), "Error during playing file", 3000).show();
return false;
}
};
android.media.MediaRecorder.OnErrorListener errorListenerForRecorder = new android.media.MediaRecorder.OnErrorListener() {
#Override
public void onError(MediaRecorder mr, int what, int extra) {
Toast.makeText(getApplicationContext(), "Error during recoding file", 3000).show();
}
};
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
btnPlay = (Button)findViewById(R.id.btnPlay);
btnRecord = (Button)findViewById(R.id.btnRecord);
progress = (ProgressBar)findViewById(R.id.progressRecorder);
mFileName = Environment.getExternalStorageDirectory().getAbsolutePath();
mFileName += "/audiorecordtest.3gp";
File file = new File(mFileName);
if(!file.exists()) btnPlay.setEnabled(false);
btnPlay.setOnClickListener(this);
btnRecord.setOnClickListener(this);
}
#Override
protected void onPause() {
super.onPause();
if(mRecorder != null) {
mRecorder.stop();
}
if(mPlayer != null) {
mPlayer.pause();
}
}
#Override
protected void onResume() {
super.onResume();
if(mRecorder != null) {
mRecorder.start();
}
if(mPlayer != null) {
mPlayer.start();
}
}
#Override
protected void onStop() {
super.onStop();
if(mRecorder != null) {
mRecorder.stop();
}
if(mPlayer != null) {
mPlayer.stop();
}
}
#Override
protected void onDestroy() {
super.onDestroy();
if(mRecorder != null) {
mRecorder.release();
mRecorder = null;
}
if(mPlayer != null) {
mPlayer.release();
mPlayer = null;
}
}
#Override
public void onClick(View v) {
if(v == btnPlay) {
onPlay(mStartPlaying);
if(mStartPlaying) {
duration = mPlayer.getDuration();
mThreadProgress = new ThreadProgress();
mThreadProgress.start();
((Button)v).setText("Stop Playing");
btnRecord.setEnabled(false);
}
else {
((Button)v).setText("Start Playing");
btnRecord.setEnabled(true);
if(mThreadProgress != null && !mThreadProgress.isAlive()) mThreadProgress.stop();
// t.interrupt();
}
mStartPlaying = !mStartPlaying;
} else if(v == btnRecord) {
onRecord(mStartRecording);
if(mStartRecording) {
mThreadProgress = new ThreadProgress();
mThreadProgress.start();
((Button)v).setText("Stop Recording");
btnPlay.setEnabled(false);
// t.start();
}
else {
((Button)v).setText("Start Recording");
btnPlay.setEnabled(true);
// t.interrupt();
if(mThreadProgress != null && !mThreadProgress.isAlive()) mThreadProgress.stop();
}
mStartRecording = !mStartRecording;
}
}
Handler handler = new Handler(new Callback() {
#Override
public boolean handleMessage(final Message msg) {
if(msg.what == 0) {
runOnUiThread(new Runnable() {
public void run() {
progress.setProgress(msg.arg1);
}
});
}
return false;
}
});
public class ThreadProgress extends Thread implements Runnable {
public int i = 0;
#Override
public void run() {
while((!this.isInterrupted() && mPlayer != null && mPlayer.isPlaying()) || (!this.isInterrupted() && mRecorder != null)) {
try {
if(duration == 1) i+=1;
else i += 100000 /duration;
Message message = new Message();
message.what = 0;
message.arg1 = i;
handler.sendMessage(message);
Thread.sleep(1000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
}
This is the example you can record audio as well as play audio
You can store recorded file in following places
1) File directory of your app
2) External directory(SD card)
3) Network