Android custom record video get setAudioSource failed - android

i'm trying to have custom preview surface view for record video from own application, this code is my test but i get this error:
setAudioSource failed
My sample code:
try {
mCamera.stopPreview();
mCamera.unlock();
mRecorder = new MediaRecorder();
mRecorder.setCamera(mCamera);
mRecorder.setAudioSource(MediaRecorder.AudioSource.CAMCORDER);
mRecorder.setVideoSource(MediaRecorder.VideoSource.CAMERA);
mRecorder.setOutputFormat(MediaRecorder.OutputFormat.MPEG_4);
mRecorder.setVideoSize(176, 144);
mRecorder.setVideoFrameRate(15);
mRecorder.setVideoEncoder(MediaRecorder.VideoEncoder.MPEG_4_SP);
mRecorder.setAudioEncoder(MediaRecorder.AudioEncoder.AMR_NB);
mRecorder.setMaxDuration(7000);
mRecorder.setPreviewDisplay(mHolder.getSurface());
mRecorder.setOutputFile(mOutputFileName);
mRecorder.prepare();
Log.v(TAG, "MediaRecorder initialized");
mInitBtn.setEnabled(false);
mStartBtn.setEnabled(true);
} catch (Exception e) {
Log.e(TAG, e.getMessage());
e.printStackTrace();
}

If you are running on Android M, then you need to request permissions to record audio on first run. To accomplish this, ask the user if you can record audio when the application starts:
private static final int MY_PERMISSIONS_REQUEST_READ_EXTERNAL_STORAGE = 29;
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
if (mContext.checkSelfPermission(Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
requestPermissions(new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE, Manifest.permission.RECORD_AUDIO},
MY_PERMISSIONS_REQUEST_WRITE_EXTERNAL_STORAGE);
} else {
Log.d("Home", "Already granted access");
initializeView(v);
}
}
#Override
public void onRequestPermissionsResult(int requestCode, #NonNull String permissions[], #NonNull int[] grantResults) {
switch (requestCode) {
case MY_PERMISSIONS_REQUEST_WRITE_EXTERNAL_STORAGE: {
if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {
Log.d("Home", "Permission Granted");
initializeView(v);
} else {
Log.d("Home", "Permission Failed");
Toast.makeText(getActivity().getBaseContext(), "You must allow permission record audio to your mobile device.", Toast.LENGTH_SHORT).show();
getActivity().finish();
}
}
// Add additional cases for other permissions you may have asked for
}
}
Also, don't forget to add the following to your Manifest:
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.RECORD_AUDIO" />

Related

Android, can't get permission for Camera dialog box to appear Marshmallow version

I can't seem to get the dialog box to pop up for camera request permission. I don't see what mistake I made. I think I followed the Android Developer document on permissions well enough yet I'm still not seeing a dialog box appear for permissions. What is wrong with the code and what can I do to fix it?
private static final int REQUEST_CAMERA_PERMISSION_RESULT = 0;
#Override
public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
// v checks for request code
if (requestCode == REQUEST_CAMERA_PERMISSION_RESULT){
// v check if request was granted or not
if (grantResults[0] != PackageManager.PERMISSION_GRANTED){
Toast.makeText(getApplicationContext(),
"Application will not run without camera services", Toast.LENGTH_SHORT).show();
}
}
}
private void connectCamera() {
CameraManager cameraManager = (CameraManager) getSystemService(Context.CAMERA_SERVICE); //connects to camera
try {
if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) { //android version "marshmallow" requires permissions
if(ContextCompat.checkSelfPermission(this, Manifest.permission.CAMERA) ==
PackageManager.PERMISSION_GRANTED) { //checks if permission is granted or not
cameraManager.openCamera(mCameraId, mCameraDeviceStateCallback, mBackgroundHandler);
} else { //if permission isn't granted. Tells user, app needs permission for camera
if(shouldShowRequestPermissionRationale(Manifest.permission.CAMERA)) {
Toast.makeText(this,
"app requires access to camera", Toast.LENGTH_SHORT).show();
}
requestPermissions(new String[] { Manifest.permission.CAMERA, Manifest.permission.RECORD_AUDIO
}, REQUEST_CAMERA_PERMISSION_RESULT);
}
} else {
cameraManager.openCamera(mCameraId, mCameraDeviceStateCallback, mBackgroundHandler);
}
} catch (CameraAccessException e) {
e.printStackTrace();
}
}

Android camera runtime permission error?

I am trying to use Camera2 api in my app even though i am checking runtime camera permission using the following code.
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
if (ActivityCompat.checkSelfPermission(this, Manifest.permission.CAMERA) == PackageManager.PERMISSION_GRANTED) {
cameraManager.openCamera(cameraId, stateCallBack, null);
} else {
if (shouldShowRequestPermissionRationale(Manifest.permission.CAMERA))
Toast.makeText(getApplicationContext(), "PLease allow the app to use camera app", Toast.LENGTH_LONG).show();
}
ActivityCompat.requestPermissions(CaptureImageActivity.this,new String[]{"android.manifest.permissin.CAMERA"}, CAMERA_REQUEST_RESULT);
} else {
cameraManager.openCamera(cameraId, stateCallBack, null);
}
#Override
public void onRequestPermissionsResult(int requestCode, String[] permission, int[] grantResult) {
switch (requestCode) {
case CAMERA_REQUEST_RESULT:
if (grantResult[0] == PackageManager.PERMISSION_GRANTED) {
try {
if (ActivityCompat.checkSelfPermission(this, Manifest.permission.CAMERA) != PackageManager.PERMISSION_GRANTED) {
//this method is created because of openCamera method below i don't understand why this method is created
return;
}
cameraManager.openCamera(cameraId, stateCallBack, null);
} catch (CameraAccessException e) {
e.printStackTrace();
}
}
if (grantResult[0] != PackageManager.PERMISSION_GRANTED)
Toast.makeText(getApplicationContext(), "camera is not granted", Toast.LENGTH_LONG).show();
break;
default:
super.onRequestPermissionsResult(requestCode, permission, grantResult);
break;
}
}
I have also permission included in the AndroidManifest.xml file.
<uses-permission android:name="android.permission.CAMERA" />
But when i run my app the permission dialog is not showing up but camera is not granted toast is showing up.
1) Why is the permission dialog not showing up?
2) Even there is no dialog showing up how is the camera is not granted toast showing up? I have searched a lot but nothing help!
Here is the working runtime permission for camera api
private static final int PERMISSIONS_REQUEST_CAPTURE_IMAGE = 1;
if (ContextCompat.checkSelfPermission(this,
Manifest.permission.CAMERA)
!= PackageManager.PERMISSION_GRANTED) {
// User may have declined earlier, ask Android if we should show him a reason
if (ActivityCompat.shouldShowRequestPermissionRationale(this, Manifest.permission.CAMERA)) {
// show an explanation to the user
// Good practise: don't block thread after the user sees the explanation, try again to request the permission.
} else {
// request the permission.
// CALLBACK_NUMBER is a integer constants
ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.CAMERA}, PERMISSIONS_REQUEST_CAPTURE_IMAGE);
// The callback method gets the result of the request.
}
} else {
}
#Override
public void onRequestPermissionsResult ( int requestCode, String[] permissions,
int[] grantResults){
switch (requestCode) {
case PERMISSIONS_REQUEST_CAPTURE_IMAGE: {
if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {
// permission was granted
Log.d("", "permission granted success");
} else {
// permission denied
Log.d("", "permission denied");
}
return;
}
}
}

start Failed in MediaRecorder.start() while call recording in xiaomi devices

Facing issue in recorder.start() while recording call generates exception start failed in some devices and in some only recording one side voice and in some it is working fine.Actually not working in xiaomi devices
Below is my code.
recorder = new MediaRecorder();
recorder.setAudioSource(MediaRecorder.AudioSource.VOICE_CALL);
recorder.setAudioSamplingRate(8000);
recorder.setAudioEncodingBitRate(12200);
recorder.setOutputFormat(MediaRecorder.OutputFormat.THREE_GPP);
recorder.setAudioEncoder(MediaRecorder.AudioEncoder.AMR_NB);
recorder.setOutputFile(audioFile.getAbsolutePath());
try {
recorder.prepare();
} catch (IllegalStateException | IOException e) {
e.printStackTrace();
}
recorder.start();
Thanks in advance
I think you forgot to check permissions. Call checkPermission() before initiate MediaRecorder.
public void checkPermission() {
// Check for permissions
int permission = ActivityCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE);
int permissionRecord = ActivityCompat.checkSelfPermission(this, Manifest.permission.RECORD_AUDIO);
// If we don't have permissions, ask user for permissions
if (permission != PackageManager.PERMISSION_GRANTED || permissionRecord != PackageManager.PERMISSION_GRANTED) {
String[] PERMISSIONS_STORAGE = {
android.Manifest.permission.READ_EXTERNAL_STORAGE,
android.Manifest.permission.RECORD_AUDIO,
android.Manifest.permission.WRITE_EXTERNAL_STORAGE
};
ActivityCompat.requestPermissions(
AudioRecorderActivity.this,
PERMISSIONS_STORAGE,
PERMISSION_REQUEST_RECORD
);
}
}
#Override
public void onRequestPermissionsResult(int requestCode,
String permissions[], int[] grantResults) {
switch (requestCode) {
case PERMISSION_REQUEST_RECORD: {
// If request is cancelled, the result arrays are empty.
if (grantResults.length > 1
&& grantResults[1] == PackageManager.PERMISSION_GRANTED && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
} else {
Toast.makeText(this, "Recording permission not found", Toast.LENGTH_LONG).show();
finish();
}
}
}
}

Failed to create directory in Android (on MarshMallow and above) devices

I am trying to create a folder on my sdcard using the following code but it fails. This is my code written in onCreate():
File test = new File(Environment.getExternalStorageDirectory(),"my_directory");
if(!test.exists())
{
try
{
if (test.mkdir())
{
Log.d("xxx", "directory created");
}
else
{
Log.d("xxx", "directory creation failed");
}
}
catch (Exception e)
{
e.printStackTrace();
}
}
else
{
Log.d("xxx","directory already present");
}
When I run the above code does not give any exception it just prints the
directory creation failed log.
I have also given the following permission,
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
I am using Xiaomi Redmi note 3 and Android version is 6.0.1.
Try this code
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
if (checkPermission()) {
//do your work
} else {
requestPermission();
}
}
}
protected boolean checkPermission() {
int result = ContextCompat.checkSelfPermission(this, android.Manifest.permission.WRITE_EXTERNAL_STORAGE);
if (result == PackageManager.PERMISSION_GRANTED) {
return true;
} else {
return false;
}
}
protected void requestPermission() {
if (ActivityCompat.shouldShowRequestPermissionRationale(this, android.Manifest.permission.WRITE_EXTERNAL_STORAGE)) {
Toast.makeText(this, "Write External Storage permission allows us to do store images. Please allow this permission in App Settings.", Toast.LENGTH_LONG).show();
} else {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
requestPermissions(new String[]{android.Manifest.permission.WRITE_EXTERNAL_STORAGE}, 100);
}
}
}
#Override
public void onRequestPermissionsResult(int requestCode, String permissions[], int[] grantResults) {
switch (requestCode) {
case 100:
if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
//do your work
} else {
Log.e("value", "Permission Denied, You cannot use local drive .");
}
break;
}
}
I know it just for API 21 (couse i wanted the same at my app, till now i do not know how to get on the sdcard)
you also need this in your manifest!!
<manifest ...>
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
...
</manifest>
Environment.getExternalStorageDirectory() declares the internal storage.
the exact path is: storage/emulated/0
you get it with:
Log.i(TAG, "path is:" + Environment.getExternalStorageDirectory().toString());

W/CameraBase﹕ An error occurred while connecting to camera: 0 on camera.open() call

I'm writing a camera app and whenever I call camera.open() the app crashes and then I get this error:
W/CameraBase﹕ An error occurred while connecting to camera: 0
Here is how I'm opening the camera:
public void getCameraInstance(){
mCamera = null;
try
{
mCamera = Camera.open(); // attempt to get a Camera instance
}
catch (Exception e)
{
// Camera is not available (in use or does not exist)
}
}
UPDATE:
If you are reading this please note that this is for the original camera API and no longer applies the the latest version of the camera api (camera2).
You should use the camera2 api from this point onwards as it has greater functionality and also has a better image processing pipeline.
NOTE ONLY VALID UP TO excluding API 21 (Lolipop) i.e. does not apply for Lolipop
and above.
You manualy uploaded your application to phone. That is why camera permission is not approved. You have to open settings->applications (or something like that) and manualy approve this permission.
In Android 6, make sure you request permission for the camera. Camera access is considered one of the 'dangerous permissions'.
To use the following method
android.hardware.Camera.open(int cameraId)
You should pass cameraId, If you want the front camera Id you can use the following method
private int findFrontFacingCamera() {
// Search for the front facing camera
int numberOfCameras = Camera.getNumberOfCameras();
for (int i = 0; i < numberOfCameras; i++) {
CameraInfo info = new CameraInfo();
Camera.getCameraInfo(i, info);
if (info.facing == CameraInfo.CAMERA_FACING_FRONT) {
cameraId = i;
cameraFront = true;
break;
}
}
return cameraId;
}
If the same camera is opened by other applications, this will throw a RuntimeException.
You must call release() when you are done using the camera, otherwise it will remain locked and be unavailable to other applications.
Your application should only have one Camera object active at a time
for a particular hardware camera.
make sure your app has permission for camera, e.g
<uses-permission android:name="android.permission.CAMERA"/>
in AndroidManifest.xml
i got the answer for this:
this is for marshmallow permission issue:
add this in your project:
step 1:
private static final int REQUEST_GET_ACCOUNT = 112;
private static final int PERMISSION_REQUEST_CODE = 200;
step2:
int currentapiVersion = android.os.Build.VERSION.SDK_INT;
if (currentapiVersion >= android.os.Build.VERSION_CODES.M) {
if (checkPermission()) {
Toast.makeText(getApplicationContext(), "Permission already granted", Toast.LENGTH_LONG).show();
} else {
requestPermission();
}
}
step3:
private boolean checkPermission() {
int result = ContextCompat.checkSelfPermission(getApplicationContext(), GET_ACCOUNTS);
int result1 = ContextCompat.checkSelfPermission(getApplicationContext(), CAMERA);
return result == PackageManager.PERMISSION_GRANTED && result1 == PackageManager.PERMISSION_GRANTED;
}
private void requestPermission() {
ActivityCompat.requestPermissions(this, new String[]{GET_ACCOUNTS, CAMERA}, REQUEST_GET_ACCOUNT);
ActivityCompat.requestPermissions(this, new String[]{WRITE_EXTERNAL_STORAGE, READ_EXTERNAL_STORAGE}, PERMISSION_REQUEST_CODE);
}
public void onRequestPermissionsResult(int requestCode, String permissions[], int[] grantResults) {
switch (requestCode) {
case PERMISSION_REQUEST_CODE:
if (grantResults.length > 0) {
boolean locationAccepted = grantResults[0] == PackageManager.PERMISSION_GRANTED;
boolean cameraAccepted = grantResults[1] == PackageManager.PERMISSION_GRANTED;
if (locationAccepted && cameraAccepted)
Toast.makeText(getApplicationContext(), "Permission Granted, Now you can access location data and camera", Toast.LENGTH_LONG).show();
else {
Toast.makeText(getApplicationContext(), "Permission Denied, You cannot access location data and camera", Toast.LENGTH_LONG).show();
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
if (shouldShowRequestPermissionRationale(WRITE_EXTERNAL_STORAGE)) {
showMessageOKCancel("You need to allow access to both the permissions",
new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
requestPermissions(new String[]{WRITE_EXTERNAL_STORAGE, READ_EXTERNAL_STORAGE},
PERMISSION_REQUEST_CODE);
}
}
});
return;
}
}
}
}
break;
}
}
private void showMessageOKCancel(String message, DialogInterface.OnClickListener okListener) {
new android.support.v7.app.AlertDialog.Builder(CaptureActivity.this)
.setMessage(message)
.setPositiveButton("OK", okListener)
.setNegativeButton("Cancel", null)
.create()
.show();
}
try to close the camera after you finish your work
in my case i use mScannerView.stopCamera() because i use it to scan code QR.
In my case your code work ,after adding this in AndroidManifest.xml
<uses-feature android:name="android.hardware.camera" />
<uses-permission android:name="android.permission.CAMERA"/>

Categories

Resources