I am trying to play an audio file
if (audioFile != null && audioFile.exists()) {
mediaPlayer = new MediaPlayer();
try {
Uri audioUri = Uri.fromFile(new File(audioFile.getAbsolutePath()));
mediaPlayer.setDataSource(getApplicationContext(),audioUri);
mediaPlayer.prepare();
mediaPlayer.start();
} catch (IOException e) {
Log.e("MediaPlayer Error", "Error while setting data source: " + e.getMessage());
} catch (IllegalArgumentException e) {
Log.e("MediaPlayer Error", "Error while preparing MediaPlayer: " + e.getMessage());
} catch (IllegalStateException e) {
Log.e("MediaPlayer Error", "Error while starting MediaPlayer: " + e.getMessage());
}
} else {
Toast.makeText(MainActivity.this, "No audio file to play", Toast.LENGTH_SHORT).show();
}
Yet I get
E/MediaPlayerNative: Unable to create media player
E/MediaPlayer Error: Error while setting data source: setDataSourceFD failed.: status=0x80000000
I thought about permission errors, so I added <uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" /> to the manifest and
if (ContextCompat.checkSelfPermission(this, Manifest.permission.READ_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.READ_EXTERNAL_STORAGE}, 1);
}
to the code of protected void onCreate(Bundle savedInstanceState) and
#Override
public void onRequestPermissionsResult(int requestCode, #NonNull String[] permissions, #NonNull int[] grantResults) {
if (requestCode == 1) {
if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
Toast.makeText(MainActivity.this, "Ja", Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(MainActivity.this, "Nein", Toast.LENGTH_SHORT).show();
}
}
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
}
outside.
I always get Nein and no window is showing up to ask for permissions, it goes straight to Nein.
The solutions here did not work so far.
I am using this in build gradle:
defaultConfig {
applicationId "com.my.program"
minSdk 27
targetSdk 33
versionCode 1
versionName "1.0"
}
Related
I have this code:
private void requestPermissionAndExport() {
if (ContextCompat.checkSelfPermission(this,
Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
ActivityCompat.requestPermissions(
this, new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE},
1);
}
}
#Override
public void onRequestPermissionsResult(int requestCode, #NonNull String[] permissions,
#NonNull int[] grantResults) {
if (requestCode == 1 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
try {
export();
} catch (IOException e) {
e.printStackTrace();
}
} else {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
}
}
public void export() throws IOException {
String csv_data = "testtest";
File root = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS);
root = new File(root, "my_csv.csv");
try {
FileOutputStream fout = new FileOutputStream(root);
fout.write(csv_data.getBytes());
fout.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
It works when I first install and launch the app. If the user deletes the csv file from the download folder and try to open the app again, and export csv again, nothing happens. Also if I generate every time differents name for the file, only the first one (after installation of the app) is created.
Why does this work only in the first instance?
#Override
public void onRequestPermissionsResult(int requestCode, #NonNull String[] permissions,
#NonNull int[] grantResults) {
if (requestCode == 1 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
try {
export();
} catch (IOException e) {
e.printStackTrace();
}
} else {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
}
}
Probably that's why. You call export() only inside onRequestPermissionsResult() and app asks for permissions only once, and remember it till you uninstall it. Try it yourself: if you clear app data from app manager it will ask again, and then export file again too.
Please help me... I'm getting
java.io.FileNotFoundException : /storage/'my external storage'/Music/'file name' : open failed: EACCES (Permission denied)
when I'm modifying music's id3 tags which are located in my sd card with jaudiotagger.
I already wrote read/write permissions on manifest file, and I wrote requesting method, permission request result callback method, and a part that modify tags when button clicked like this.
private void requestExternalStoragePermissions() {
if (Build.VERSION.SDK_INT >= 23) {
if (checkSelfPermission(Manifest.permission.WRITE_EXTERNAL_STORAGE) == PackageManager.PERMISSION_GRANTED) {
Toast.makeText(this, "Permission granted to write your External storage", Toast.LENGTH_SHORT).show();
start();
}
else {
ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, 1);
}
}
}
#Override
public void onRequestPermissionsResult(int requestCode, String permissions[], int[] grantResults) {
switch (requestCode) {
case 1 : {
// If request is cancelled, the result arrays are empty.
if (grantResults.length > 0&&grantResults[0] == PackageManager.PERMISSION_GRANTED) {
Toast.makeText(this, "Permission granted", Toast.LENGTH_SHORT).show();
start();
}
else {
Toast.makeText(this, "Permission denied to access your External storage", Toast.LENGTH_SHORT).show();
}
return;
}
}
}
savebutton.setOnClickListener(new Button.OnClickListener(){
#Override
public void onClick(View view){
try{
AudioFile f = AudioFileIO.read(file);
Tag tag = f.getTag();
tag.setField(FieldKey.TITLE,editText1.getText().toString());
tag.setField(FieldKey.ALBUM,editText2.getText().toString());
tag.setField(FieldKey.ARTIST,editText3.getText().toString());
tag.setField(FieldKey.ALBUM_ARTIST,editText4.getText().toString());
tag.setField(FieldKey.YEAR,editText5.getText().toString());
tag.setField(FieldKey.DISC_NO,editText6.getText().toString());
tag.setField(FieldKey.TRACK,editText7.getText().toString());
tag.setField(FieldKey.LYRICS,editText8.getText().toString());
f.commit();
Toast.makeText(getApplicationContext(), "Tag Saved", Toast.LENGTH_SHORT).show();
} catch(Exception e){
e.printStackTrace();
}
}
});
How can I fix this?
In Android 4.4 and higher, editing files on the sd card is not possible anymore. I had the same issue..
The only workaround is to copy the file to the internal storage, modify it and move it back.
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());
I have already added record_audio permission in the manifest but still error prevails..kindly help!!
com.sinch.android.rtc.MissingPermissionException: Requires permission: android.permission.RECORD_AUDIO
at com.sinch.android.rtc.internal.client.calling.DefaultCallClient.throwIfMissingPermission(DefaultCallClient.java:412)
at com.sinch.android.rtc.internal.client.calling.DefaultCallClient.call(DefaultCallClient.java:150)
at com.sinch.android.rtc.internal.client.calling.DefaultCallClient.callUser(DefaultCallClient.java:102)
at com.sinch.android.rtc.internal.client.calling.DefaultCallClient.callUser(DefaultCallClient.java:97)
at com.example.ram.dummy.CallActivity$1.onClick(CallActivity.java:45)
at android.view.View.performClick(View.java:5697)
at android.widget.TextView.performClick(TextView.java:10826)
at android.view.View$PerformClick.run(View.java:22526)
at android.os.Handler.handleCallback(Handler.java:739)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:158)
at android.app.ActivityThread.main(ActivityThread.java:7224)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1230)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1120)
Check permission added in manifest.xml or not. If you dont have check permission . Please add permission. I hope it will work
<uses-permission android:name="android.permission.RECORD_AUDIO" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
Otherwise I suggest to check below code snippest for Recording audio and check runtime permission :
public static final int RequestPermissionCode = 1;
check permission of Audio RECORD and start recording '
if(checkPermission()) {
AudioSavePathInDevice =
Environment.getExternalStorageDirectory().getAbsolutePath() + "/" +
CreateRandomAudioFileName(5) + "AudioRecording.3gp";
MediaRecorderReady();
try {
mediaRecorder.prepare();
mediaRecorder.start();
} catch (IllegalStateException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
buttonStart.setEnabled(false);
buttonStop.setEnabled(true);
Toast.makeText(MainActivity.this, "Recording started",
Toast.LENGTH_LONG).show();
} else {
requestPermission();
}
private void requestPermission() {
ActivityCompat.requestPermissions(MainActivity.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(MainActivity.this, "Permission Granted",
Toast.LENGTH_LONG).show();
} else {
Toast.makeText(MainActivity.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;
}
For more information Refer this Android - Audio Capture
I hope it will be work fine.
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" />