Android MediaPlayer unknown error - java

I am creating a MediaPlayer instance in MainActivity's onCreate() method like this
MediaPlayer mPlayer = MediaPlayer.create(this, Uri.fromFile(new File("/storage/emulated/0/soundrecorder/My recording #26.wav")));
It is created successfully but I get this error:
07-06 18:33:44.266 18366-18366/com.audiorecorder.wel.voicerecorder E/MediaPlayer-JNI: JNIMediaPlayerFactory: bIsQCMediaPlayerPresent 0
07-06 18:33:44.267 18366-18366/com.audiorecorder.wel.voicerecorder E/MediaPlayer-JNI: JNIMediaPlayerFactory: bIsQCMediaPlayerPresent 0
Also tried this but the same error on logcat:
MediaPlayer mp = new MediaPlayer();
try {
mp.setDataSource(this, Uri.fromFile(new File("/storage/emulated/0/soundrecorder/My recording #26.wav")));
} catch (IOException e) {
e.printStackTrace();
}
mp.prepareAsync();
mp.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
#Override
public void onPrepared(MediaPlayer mp) {
mp.start();
}
});
I have tried different audio files with different formats but result is the same error. I have also tried searching the answer on stackoverflow but could not resolve the issue. Can you help me on this?

It seems there is some issue with your file. Update that with this :
musicUri = android.provider.MediaStore.Audio.Media.EXTERNAL_CONTENT_URI;
And then follow these steps:
1. getLoaderManager().initLoader(0,null,this);
2. #Override
public Loader<Cursor> onCreateLoader(int id, Bundle args) {
switch (id){
case 0 : return new CursorLoader(getApplicationContext(),musicUri,null,null,null,null);
return new Loader<>(this);
}
3. #Override
public void onLoadFinished(Loader<Cursor> loader, Cursor data) {
switch (loader.getId()) {
case 0 :
if(data != null && data.moveToFirst()) {
songTitleColumnIndex = data.getColumnIndex(MediaStore.Audio.Media.TITLE);
do {
songTitle = data.getString(songTitleColumnIndex);
songsList.add(songTitle);
} while (data.moveToNext());
}
break;
So the SongTitles are being put in the SongList which is an ArraList of String Type.
Hope This Helps.

Try using a FileInputStream to start your MediaPlayer with a FileDescriptor instead:
String yourFilePath = "/wherever/your/file/is.wav";
MediaPlayer mPlayer = new MediaPlayer();
try{
FileInputStream inputStream = new FileInputStream(yourFilePath);
mPlayer.setDataSource(inputStream.getFD());
inputStream.close();
mPlayer.prepare();
mPlayer.start();
}catch (IOException e){
Log.e("IOException", e.getMessage());
}

Related

Media player to return file from res folder

If someone can help me with this problem:
I'm trying to get the song from res folder in this method
private void playSound(String file) {
Context context = binding.playBtn.getContext();
Resources resources = context.getResources();
int sound_id = resources.getIdentifier(file,"raw",
context.getPackageName());
MediaPlayer mediaPlayer = MediaPlayer.create(context,sound_id);
mediaPlayer.start();
}
Then to call this method here
public void bind(CalmScreenItem calmScreenItem) {
binding.mainText.setText(calmScreenItem.mainText);
binding.subtext.setText(calmScreenItem.subtext);
binding.itemImg.setImageDrawable(getImage(calmScreenItem.imgUrl));
binding.container.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
playSound(calmScreenItem.soundUrl);
}
});
}
Then finally call in the main fragment in the list**
private List<CalmScreenItem> getItems() {
List<CalmScreenItem> calmScreenItems = new ArrayList<>();
calmScreenItems.add(new CalmScreenItem(getString(R.string.main_item1),getString(R.string.sub_item1),"guide","free.mp3"));
calmScreenItems.add(new CalmScreenItem(getString(R.string.main_item2),getString(R.string.sub_item2),"mindfull","mindfull.mp3"));
return calmScreenItems;
}
The output should be when clicked on button to play different sound from the res folder
Can someone please help me! Thanks
There is a mistake in the way you are fetching the files
YOu would need to use an Uri and pass that to the MediaPlayer for it to be able to play your music . Also store y our audio files in raw subdirectory
For eg:
Uri mediaPath = Uri.parse("android.resource://" + getPackageName() + "/" + R.raw.filename);
try {
mMediaPlayer.setDataSource(getApplicationContext(), mediaPath);
mMediaPlayer.prepare();
mMediaPlayer.start();
} catch (Exception e) {
e.printStackTrace();
}
Ref : StackOverflow questionon playing music from raw resource

SeekTo initially in Android's Mediaplayer makes mediaplayer not work

This is the method where I create my Mediaplayer and set it's source, but directly after I call seekTo it does't play anymore (If I give it some time-depends on the audio, it worksm--> Conclusion after debug).
public void makeAudio(boolean isInit){
try{
if(!isInit){
mediaPlayer = new MediaPlayer();
}
soundSource = episode.getAudio();
mediaPlayer.setDataSource(soundSource);
mediaPlayer.prepareAsync();
mediaPlayer.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
#Override
public void onPrepared(MediaPlayer mp) {
soundLength = mediaPlayer.getDuration();
seekBar.setMax(soundLength/1000);
mediaPlayer.seekTo(progress);//the problem I guess
}
});
}catch (Exception e){
e.printStackTrace();
}
}
It shows me this error message:
E/MediaPlayerNative: Attempt to perform seekTo in wrong state: mPlayer=0x706c23ebc0, mCurrentState=0
I would like to have any suggestion about this, because I want to make my mediaplayer go to the progress value(I get it from my intent).
I suggest you to use ExoPlayer, it is an improved version of MediaPlayer and addListener works better for online audio.
You have to add listener until it is prepared and only then you can get the duration:
exoPlayer.addListener(new Player.Listener() {
#Override
public void onPlayerStateChanged(boolean playWhenReady, int playbackState) {
if (playbackState == ExoPlayer.STATE_READY) {
long realDurationMillis = exoPlayer.getDuration();
seekBar.setMax((int)realDurationMillis/1000);
dialog.dismiss();
}
if (playbackState == ExoPlayer.STATE_ENDED){
performEndExoPlayer();
}
}
});
Here is an example you can have a look https://developer.android.com/codelabs/exoplayer-intro#5

How to use MediaPlayer which plays music stored in a folder found in the asset

I am creating an android app from android studio.
My intention is to have a function to play different songs depending on the string argument.
MediaPlayer mysound;
public void play(String song){
mysound = Mediaplayer.create(this, "../../../../asset/soundlib/" + song);
mysound.play();
}
I tried the R.assets.song. It just does not work.
Is there a way to have the song named C.mp3? It says that they should not be capitalized and all of the arguments taken are basically chords like C A F...
Thank you
For android java use
void test_mp(String file_name)
{
MediaPlayer mediaPlayer = null;
mediaPlayer = new MediaPlayer();
try {
AssetFileDescriptor afd = act.getAssets().openFd(file_name);
mediaPlayer.setDataSource(afd.getFileDescriptor(), afd.getStartOffset(), afd.getLength());
afd.close();
mediaPlayer.prepare();
} catch (final Exception e) {
e.printStackTrace();
}
mediaPlayer.start();
}
So for your case, you can call it like test_mp("SoundLib/A.mp3");
Try below code for play assets song :
fun playSound(context: Context, assetsFileName: String?) {
try {
val mediaPlayer = MediaPlayer()
val descriptor: AssetFileDescriptor = context.getAssets().openFd(assetsFileName!!)
mediaPlayer.setDataSource(
descriptor.getFileDescriptor(),
descriptor.getStartOffset(),
descriptor.getLength()
)
descriptor.close()
mediaPlayer.prepare()
mediaPlayer.isLooping = false
mediaPlayer.start()
} catch (e: Exception) {
e.printStackTrace()
}
}
Thanks

setDataSource with Uri causes NullPointerException

Well, this is the onClick method of a button:
public void aggiungi (View v){
Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
intent.setType("audio/*");
startActivityForResult(Intent.createChooser(intent, "Select"), PICK_AUDIO_REQUEST_CODE);
}
And outside I've handled the output:
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == PICK_AUDIO_REQUEST_CODE){
if (resultCode == RESULT_OK){
Uri uri_to_use = data.getData();
setAudioToButton(uri_to_use);
}
}
}
And here's the setAudioToButton method called
public void setAudioToButton(final Uri audio){
PercentRelativeLayout percentRelativeLayout = (PercentRelativeLayout)findViewById(R.id.main_layout);
PercentRelativeLayout.LayoutParams layoutParams = new PercentRelativeLayout.LayoutParams(43, 12);
layoutParams.addRule(PercentRelativeLayout.ALIGN_PARENT_RIGHT);
layoutParams.addRule(PercentRelativeLayout.BELOW, R.id.quattro);
Button button = new Button(this);
button.setLayoutParams(layoutParams);
PercentRelativeLayout.LayoutParams layoutParams1 = (PercentRelativeLayout.LayoutParams)button.getLayoutParams();
PercentLayoutHelper.PercentLayoutInfo percentLayoutInfo = layoutParams1.getPercentLayoutInfo();
percentLayoutInfo.heightPercent = 0.12f;
percentLayoutInfo.widthPercent = 0.43f;
percentLayoutInfo.topMarginPercent = 0.063f;
percentLayoutInfo.leftMarginPercent = 0.007f;
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if (mediaPlayer != null){mediaPlayer.stop();}
try {mediaPlayer.setDataSource(getBaseContext(), audio);} catch (IOException error){error.printStackTrace();}
try {
mediaPlayer.prepare();
} catch (IOException e) {
e.printStackTrace();
}
mediaPlayer.start();
}
});
button.setText("start");
percentRelativeLayout.addView(button);
}
The problem is when I click on the new button to make it sound, I have a NullPointerException:
08-22 02:32:43.164 11880-11880/com.example.utente.usefulsounds E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.utente.usefulsounds, PID: 11880
Theme: themes:{}
java.lang.NullPointerException: Attempt to invoke virtual method 'void android.media.MediaPlayer.setDataSource(android.content.Context, android.net.Uri)' on a null object reference
at com.example.utente.usefulsounds.MainActivity$1.onClick(MainActivity.java:182)
at android.view.View.performClick(View.java:5204)
at android.view.View$PerformClick.run(View.java:21158)
at android.os.Handler.handleCallback(Handler.java:739)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:148)
at android.app.ActivityThread.main(ActivityThread.java:5461)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616)
I am wondering why this happens, I can't understand
**
EDIT:
**
I've put this in the onCreate method
if (ContextCompat.checkSelfPermission(getApplicationContext(), android.Manifest.permission.READ_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED){
ActivityCompat.requestPermissions(this, new String[]{android.Manifest.permission.READ_EXTERNAL_STORAGE}, READ_EXTERNAL_STORAGE_REQUEST_CODE);
}
But it didn't worked
Now I've tried in a different way: intead of passing an Uri to the MediaPlayer, I've passed a filedescriptor:
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if (mediaPlayer != null){mediaPlayer.stop();}
File file = new File(audio.getPath());
FileInputStream fileInputStream;
try {
fileInputStream = new FileInputStream(file);
try {mediaPlayer.setDataSource(fileInputStream.getFD());} catch (IOException error){error.printStackTrace();}
}catch (IOException ioe){button.setText("FILE ERROR");}
try {
mediaPlayer.prepare();
} catch (IOException e) {
e.printStackTrace();
}
mediaPlayer.start();
}
});
The button appears with the text "select", so there isn't any problem with the file (otherwise it should have been "file error"), but when I click on that I still have a crash caused by a NullPointerException with mediaPlayer. Why this? I can't understand
HERE'S THE ANSWER
Instead of doing a setDataSource() method you have to use simply a create() method :)
Eg.
MediaPlayer.create(getApplicationContext(), yourAudioUri).start();
Happy coding and have fun :)

Problems rendering video only in Samnsung GT-I8260 using SurfaceView. IOException: Prepare failed.: status=0x1

I'm developing an app that uses a ViewPager with one video in each page. Everything works well in every smartphone but it doesn't work in Samnsung GT-I8260 with Android 4.1.2
So in this smartphone, when I compile it returns IOException: Prepare failed.: status=0x1 and it points to mMediaPlayer.prepare();
Now the code is the next:
//First of all I initilize MediaPlayer and I handle the Callback method for SurfaceView
mMediaPlayer = new MediaPlayer();
mSurfaceView.getHolder().addCallback(new SurfaceHolder.Callback() {
#Override
public void surfaceDestroyed(SurfaceHolder holder) {
mMediaPlayer.release();
}
#Override
public void surfaceCreated(SurfaceHolder holder) {
holder.setSizeFromLayout();
playVideoDelay();
}
#Override
public void surfaceChanged(SurfaceHolder holder,
int format, int width, int height) {
}
});
//The app plays the first video with the next method
private void playVideoDelay() {
try {
Uri path = Uri.parse("android.resource://com.casabioclimatica/raw/"+mVideoId);
mMediaPlayer.reset();
mMediaPlayer.setDataSource( mActivity, path);
mMediaPlayer.setDisplay(mSurfaceView.getHolder());
mMediaPlayer.prepare();
if (Build.VERSION.SDK_INT >= 16)
mMediaPlayer
.setVideoScalingMode(MediaPlayer.VIDEO_SCALING_MODE_SCALE_TO_FIT_WITH_CROPPING);
mMediaPlayer.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
#Override
public void onPrepared(MediaPlayer mp) {
mp.start();
}
});
// fis = new FileInputStream(new File(path.getPath()));
//mMediaPlayer.setDataSource(fis.getFD());
} catch (Exception e) {
e.printStackTrace();
}
}
//When ViewPager changes it pages I call this method:
public void playVideoDelay(int videoId) {
try {
Uri path = Uri.parse("android.resource://com.casabioclimatica/raw/"+videoId);
mMediaPlayer.reset();
mMediaPlayer.setDataSource( mActivity, path);
mMediaPlayer.setDisplay(mSurfaceView.getHolder());
mMediaPlayer.prepare();
if (Build.VERSION.SDK_INT >= 16)
mMediaPlayer
.setVideoScalingMode(MediaPlayer.VIDEO_SCALING_MODE_SCALE_TO_FIT_WITH_CROPPING);
mMediaPlayer.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
#Override
public void onPrepared(MediaPlayer mp) {
mp.start();
}
});
} catch (Exception e) {
e.printStackTrace();
}
}
Hope somebody has had something similar and knows the proper solution!
Thanks!
After a lot of code changes,I have found the problem in this smartphone, this is because of the maximum resolution. In this case it has 800 x 480 px and I was using 1080 x 800, it was too much and the Dalvik machine interprets that case like this file doesn't exist or doesn't work. I have changed the high and width size of the file and it works like charm!
So for any similar case: Pay attention to your maximum screen supported resolution and try to use this size to avoid any strange error when you render a video.
Hope it helps!

Categories

Resources