Android MediaPlayer: Play Audio Resource in Raw Based on URI - android

The problem I am trying to solve is in an activity that needs to play back audio files. Most of the files will be user created (and saved into external storage), and therefore played with the following code (based on Google's example code):
MediaPlayer mPlayer = new MediaPlayer();
mPlayer.setDataSource(filename);
mPlayer.prepare();
mPlayer.start();
Some of the audio files, though, are going to be included with the app, are usually played with the following code:
MediaPlayer mPlayer = MediaPlayer.create(getBaseContext(), R.raw.filename);
mPlayer.prepare();
mPlayer.start();
The issue is that I would like to be able to play the audio files in the raw folder in the same way that I am playing the user created files since I don't necessarily know which will be needed. I tried tried to get the URI of the audio file in the raw folder and play it with the following code:
Uri uri = Uri.parse("android/resource://com.my.package/" + R.raw.filename);
MediaPlayer mPlayer = new MediaPlayer();
mPlayer.setDataSource(uri.toString());
mPlayer.prepare();
mPlayer.start();
But nothing happens. No error messages, no playing audio.
I outlined what I thought was the simplest solution, but I am willing to go another route if it accomplishes the task. Any assistance is greatly appreciated.

I've managed to get it working, here is the code I used.
mMediaPlayer = new MediaPlayer();
Uri mediaPath = Uri.parse("android.resource://" + getPackageName() + "/" + R.raw.filename);
try {
mMediaPlayer.setDataSource(getApplicationContext(), mediaPath);
mMediaPlayer.prepare();
mMediaPlayer.start();
} catch (Exception e) {
e.printStackTrace();
}
I see two problems I see with your code. The first is that "android/resource" needs to become "android.resource"
The second is that setDataSource(String) won't work in this case due to the fact that you need context to use raw files as otherwise it tries to open the file incorrectly. (See the top answer in MediaPlayer.setDataSource(String) not working with local files)

final int[] song = {R.raw.letmeloveyou,R.raw.aarti,R.raw.answer};
final MediaPlayer mp = new MediaPlayer();
lv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
try {
if (true == mp.isPlaying()) {
mp.stop();
mp.reset();
Toast.makeText(getBaseContext(), "Again Playing", Toast.LENGTH_LONG).show();
mp.setDataSource(Result.this, Uri.parse("android.resource://" + getPackageName() + "/" + song[position]));
mp.prepare();
mp.start();
} else {
Toast.makeText(getBaseContext(), "Playing", Toast.LENGTH_LONG).show();
mp.setDataSource(Result.this, Uri.parse("android.resource://" + getPackageName() + "/" + song[position]));
mp.prepare();
mp.start();
}
} catch (Exception e) {
Toast.makeText(getBaseContext(),e.toString(),Toast.LENGTH_LONG).show();
}
}
});

When I used toString() in Uri it failed, when I used direct Uri it played well.
Uri musicUri = Uri.parse("android.resource://" + context.getPackageName() + "/" + resourceID);
Log.d(TAG, "musicUri: " + musicUri);
mediaPlayer.setDataSource(context, musicUri);

Related

No response on full screen activity (different android version?)

Here is my code on full screen video.
It work just fine in emulator but not in real android phone.
public void videoClick(View view){
Intent mIntent = new Intent(getBaseContext(),VideoFullscreenActivity.class);
videoUri = Uri.parse("android.resource://tk.myessentialoils.ideasapp/raw/"+ contentStringList[count][2]);
mIntent.putExtra("videoUri",videoUri);
startActivity(mIntent);
}
My thinking is that the Uri problem.
Xiaomi android have different uri than other.
Some Huawei phone also not functioning well.
So is there any alternative to get the file instead?
Perhaps a work around that will work on all version of android.
Edit 1
as per Vivek Mishra suggestions,
tried the below
Intent mIntent = new Intent(getBaseContext(),VideoFullscreenActivity.class);
String path = "file:///android_asset/"+ contentStringList[count][2];
videoUri = Uri.parse(path);
mIntent.putExtra("videoUri",videoUri);
startActivity(mIntent);
However i got this error >> Can't play this video
as per How to load videos from assets folder? (to play them with VideoView) asset folder cannot play video
Edit 2
same question as Nullpointerexception, i cant get the Media player to work with my code.
Uri videoUri = getIntent().getParcelableExtra("videoUri");
VideoView videoView=findViewById(R.id.myvideoview);
videoView.setVideoURI(videoUri);
//videoView.setVideoURI(Uri.parse("android.resource://" + getPackageName() + "/" + R.raw.full));
MediaController mediaController = new MediaController(this);
videoView.setMediaController(mediaController);
videoView.start();
videoView.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
#Override
public void onPrepared(MediaPlayer mp) {
mp.setLooping(true);
}
});
how do i implement the below code in my code above.
AssetFileDescriptor afd;
try {
afd = getAssets().openFd("v.mp4");
player.setDataSource(afd.getFileDescriptor(),afd.getStartOffset(),
afd.getLength());
player.prepareAsync();
player.setOnPreparedListener(new OnPreparedListener() {
#Override
public void onPrepared(MediaPlayer mp) {
mp.start();
}
});
} catch (Exception e) { e.printStackTrace();}

Uri MediaPlayer Android Internal Storage

I want to integrate my app with a MediaPlayer, but I can't play music that are in the internal storage.
Actually I have only 1 song in the "Music" folder. I can't play it.
This is my code:
Uri uri = MediaStore.Audio.Media.INTERNAL_CONTENT_URI;
MediaPlayer mediaPlayer = new MediaPlayer();
mediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC;
try {
mediaPlayer.setDataSource(this, uri);
mediaPlayer.prepare();
} catch (IOException e) {
e.printStackTrace();
}
mediaPlayer.start();
This techniques is ok if and only if you want to play one sound depending on your condition. Set URI as follow:
Uri soundUri = Uri.parse("android.resource://" + getPackageName()
+ "/" + R.raw.sound);
other way would be:
Uri uri = MediaStore.Audio.Media.getContentUriForPath(pathToFolderSDCard);

What is wrong with my music player for Android ???? It's going to CATCH in the try\catch statement every single time WHY?

I'm done my Android app, just need to add some looping background music. Here is my method for playing the song
public void playAudio(){
path = "android.resource://" + getPackageName() + "/" + R.raw.music1;
//set up MediaPlayer
MediaPlayer mp = new MediaPlayer();
try {
mp.setDataSource(path);
mp.prepare();
mp.setLooping(true);
mp.setVolume(100, 100);
mp.start();
} catch (Exception e) {
e.printStackTrace();
Log.d("NOTE WORKEING","NOT WORKING");
}
}
It's not working....It's going to catch everytime, and I don't know why. Please help me. Music1 is an mp3 file.
Thank you
Make sure your music1 file is in a Android playable Android format.
Then just use this code:
MediaPlayer mediaPlayer = MediaPlayer.create(YourActivity.this, R.raw.music1);
try {
mediaPlayer.setLooping(true);
mediaPlayer.setVolume(100, 100);
mediaPlayer.start();
}
catch (Exception e) {
e.printStackTrace();
Log.d("NOT WORKEING","NOT WORKING");
}
You don't even need to call prepare() method.
I tested it with an mp3 file and it works perfectly.
If #Squonk's answer does not work, then the problem has to do with trying to start the music file before the MediaPlayer has prepared it. Try changing the MediaPlayer's start code to the following:
mp.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
#Override
public void onPrepared(MediaPlayer mp) {
start();
}
});
Let me know if this helps, I have a good amount of experience with the MediaPlayer class and can help you troubleshoot.
Using mp.setDataSource(path) requires a valid filesystem path or URL.
In your case, path is a string representation of a Uri in which case you need to use a different approach.
Try setDataSource(Context context, Uri uri). You'll obviously need to provide a valid Context and parse your path variable into a Uri. Example...
mp.setDataSource(getApplicationContext(), Uri.parse(path));
Also change the path to...
path = "android.resource://" + getPackageName() + "/raw/music1";

Cannot play video after downloading from server

my media recorder is recording video after recording i am previewing my video (fine).
now uploaded this video on my local http server .
and finally getting this from server to play in a videoview but it shows cannot play video.
any suggestion where actually mistake is...
Thanx for help.
MediaRecorder
this.mediaRecorder = new MediaRecorder();
this.mediaRecorder.setCamera(this.camera);
camera.unlock();
this.mediaRecorder.setCamera(camera);
this.mediaRecorder.setOrientationHint(90);
this.mediaRecorder.setAudioSource(MediaRecorder.AudioSource.DEFAULT);
this.mediaRecorder.setVideoSource(MediaRecorder.VideoSource.DEFAULT);
CamcorderProfile camcorderProfile_HQ = CamcorderProfile.get(CamcorderProfile.QUALITY_480P);
this.mediaRecorder.setProfile(camcorderProfile_HQ);
this.mediaRecorder.setOutputFile(this.initFile().getAbsolutePath());
this.mediaRecorder.setMaxDuration(60000); // Set max duration 60 sec.
this.mediaRecorder.setMaxFileSize(5000000);
this.mediaRecorder.setPreviewDisplay(this.cameraPreview.getHolder().getSurface());
try {
this.mediaRecorder.prepare();
// start the actual recording
// throws IllegalStateException if not prepared
this.mediaRecorder.start();
Toast.makeText(this, R.string.recording, Toast.LENGTH_SHORT).show();
// enable the stop button by indicating that we are recording
this.toggleButtons(true);
} catch (Exception e) {
Log.wtf(TAG, "Failed to prepare MediaRecorder", e);
Toast.makeText(this, R.string.cannot_record, Toast.LENGTH_SHORT).show();
this.releaseMediaRecorder();
}
Video view
Uri uri = Uri.parse("/data/data/com.example.mediarecorder/files/"+ messageList.get(position)); //do not add any extension
video.setVideoURI(uri);
video.requestFocus();
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
video.setKeepScreenOn(true);
System.out.println(uri + " "+ uri.getEncodedAuthority()+ " "+ uri.decode(data_type) + " "+ uri.getUserInfo() + " "+ uri.describeContents());
video.start();
You can't play video from internal storage via videoview, as the file does not have world readable permission. You have to create custom video player using surfaceView and media player class. Then you have to create a file descriptor of the file you need to play and pass that to mediaPlayer.setDataSource():
FileInputStream inputStream = new FileInputStream(videoPath);
//assume videoPath = getFilesDir().getAbsolutePath()) + File.separator + "Video.mp4"
mp.setDataSource(inputStream.getFD());
mp.prepareAsync();
try {
mp.setOnPreparedListener(new OnPreparedListener() {
#Override
public void onPrepared(MediaPlayer mplayer) {
if (mp != null) {
mp.start();
}
}
});

Playing Audio from Cache Directory

When playing audio from sdcard, MediaPlayer plays the file. But when playing from getCacheDir() it is an error. Is my conclusion right that MediaPlayer can't play files from getCacheDir() ?
Here's a code snippet:
private void startPlaying(String asAudioFileName) {
File fFile = new File(VocaPreview.this.getCacheDir() + "/" + asAudioFileName.toLowerCase() + ".mp3");
if(!fFile.isFile()) {
Toast.makeText(getApplicationContext(), "File not found", Toast.LENGTH_SHORT).show();
} else {
try {
FileInputStream fisAudio = new FileInputStream(fFile);
//fmpAudio.setDataSource(VocaPreview.this.getCacheDir() + "/" + asAudioFileName.toLowerCase() + ".mp3");
//fmpAudio.setDataSource("/sdcard/2.mp3");
fmpAudio.setDataSource(fisAudio.getFD());
fmpAudio.prepare();
fmpAudio.start();
} catch(IOException ioe) {
Log.e("START PLAYING", ioe.getMessage());
}
}
}
UPDATE:
I just read from this Blog and solved my problem, inorder for me to play audio inside a cache, I added this line and that's it. Hope this helps anyone in the future. Here is the method.
File file = new File(filepath)
file.setReadable(true, false);
Here's a function that also works on API levels < 9:
Runtime.getRuntime().exec("chmod 644 "+ outputFile.getAbsolutePath());

Categories

Resources