Uri MediaPlayer Android Internal Storage - android

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);

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();}

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";

Android MediaPlayer: Play Audio Resource in Raw Based on URI

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);

How to play video from raw folder with Android device?

Please help,
How to play videos in android device from raw folder for offline mode?
Successful example1: I can play the video from SDcard used the below code.
Intent intent = new Intent(Intent.ACTION_VIEW);
String type = "video/mp4";
Uri uri = Uri.parse("file:///sdcard/test.mp4");
intent.setDataAndType(uri, type);
startActivity(intent);
Failed example2:
Question: May I put the test.mp4 to res/raw folder?
Intent intent = new Intent(Intent.ACTION_VIEW);
String type = "video/mp4";
Uri uri = Uri.parse("android.resource://" + getPackageName() + "/" + R.raw.taipei);
intent.setDataAndType(uri, type);
startActivity(intent);
Have anyone can help me? Please.
Copy the video into your project's res/raw folder. Create raw folder under res folder. It must be in a supported format (3gp, wmv, mp4 ) and named with lower case, numerics, underscores and dots in its filename likewise:video_file.mp4.
VideoView view = (VideoView)findViewById(R.id.videoView);
String path = "android.resource://" + getPackageName() + "/" + R.raw.video_file;
view.setVideoURI(Uri.parse(path));
view.start();
Create videoView in your xml file.
// To get files from any resource folder (eg: raw, drawable, etc.)
// Use the resource id
int rawId = getResources().getIdentifier(file_name_without_extension, "raw", getPackageName());
// URI formation
String path = "android.resource://" + getPackageName() + "/" + rawId;
// Set the URI to play video file
videoView.setVideoURI(Uri.parse(path));
Check this solution How to play videos in android from assets folder or raw folder?
VideoView videoHolder = new VideoView(this);
//if you want the controls to appear
videoHolder.setMediaController(new MediaController(this));
Uri video = Uri.parse("android.resource://" + getPackageName() + "/"
+ R.raw.your_raw_file); //do not add any extension
//if your file is named sherif.mp4 and placed in /raw
//use R.raw.sherif
in my code "applicationdemo" is the the name of my video file.
String video_url = "android.resource://" + context.getPackageName() + "/" + R.raw.applicationdemo;
final VideoView videoView = findViewById(R.id.dialog_video);
Uri videoUri = Uri.parse(video_url);
MediaController mediaController= new MediaController(context);
mediaController.setAnchorView(videoView);
videoView.setMediaController(mediaController);
videoView.setVideoURI(videoUri);
videoView.requestFocus();
videoView.start();
I struggled with this for dynamic video names. The solution that worked for me was:
//Somewhere set the video name variable
String video+name="myvideo";
//setup up and play video
VideoView videoView=(VideoView)findViewById(R.id.video);
videoView.setVisibility(View.VISIBLE);
String uriPath = "android.resource://"+getPackageName()+"/raw/"+ video_name;
Uri UrlPath=Uri.parse(uriPath);
MediaController mediaController = new MediaController(this);
mediaController.setAnchorView(videoView);
videoView.setMediaController(mediaController);
videoView.setVideoURI(UrlPath);
videoView.setOnPreparedListener(new OnPreparedListener() {
public void onPrepared(MediaPlayer mediaPlayer) {
if (position == 0) {
try{
videoView.requestFocus();
videoView.start();
}catch (Exception e){
System.out.printf("Error playing video %s\n", e);
}
}else{
videoView.pause();
}
}
});
And in XML
<VideoView android:layout_width="300dp"
android:id="#+id/video"
android:layout_height="300dp"
android:orientation="horizontal"
android:layout_gravity="center"
android:keepScreenOn="true"
/>
i think , everyone gave an answer, but doesn't explain the scenario. The main problem here is, If im not mistaken , Android assume that the video coming from your SD Card is dynamic, where in it could be possible , that the format is not supported or supported, thus it enables / ask you to select or open for other third party media software.
While anything you play UNDER RAW folder, requires a handler such as videoview or built in media player which leads to conclusion that anything you put in your RAW folder should be supported / readable by the Android OS.
However , the thread starter here wants that his RAW files , to be played using a third party media player.
This Solution will exactly helps you that what you want.
VideoView myVideo;
private MediaController media_control;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
myVideo = (VideoView) findViewById(R.id.playVideo);
Uri uri = Uri.parse("android.resource://" + getPackageName() + "/" + R.raw.bootanimation_nexus);
media_control = new MediaController(this);
myVideo.setMediaController(media_control);
myVideo.setVideoURI(uri);
myVideo.start();
}
player = ExoPlayerFactory.newSimpleInstance(requireActivity(), new DefaultTrackSelector(), new DefaultLoadControl());
Uri uri = RawResourceDataSource.buildRawResourceUri(getOfflineVideo(offlinePosition));
MediaSource mediaSource = new ExtractorMediaSource(uri, new DefaultDataSourceFactory(requireActivity(),
"MyExoplayer"), new DefaultExtractorsFactory(), null, null);
//setup player with mediaSource

Display an image in default media player of Android

Here is my code. First I recorded an audio file and started playing it. For playing the audio file
/**
*
* play the recorded audio
*
*/
public void playAudio() {
try {
Intent intent = new Intent(android.content.Intent.ACTION_VIEW);
Uri data = Uri.parse(path);
intent.setDataAndType(data, "audio/mp3");
startActivity(intent);
} catch (ActivityNotFoundException e) {
e.printStackTrace();
} catch (Exception e) {
// TODO: handle exception
}
}
and the output is calling the default media player of device. Here I need to show an image in that media player in the place of album image.
Here is an image of what I need:
The default media player is using the following code to retrieve the album art of a song.
Uri sArtworkUri = Uri.parse("content://media/external/audio/albumart");
Uri uri = ContentUris.withAppendedId(sArtworkUri, album_id);
ContentResolver res = context.getContentResolver();
InputStream in = res.openInputStream(uri);
Bitmap artwork = BitmapFactory.decodeStream(in);
where album_id is the albumd id of the song. So in order to show an album art the default player should know the album id and check if there is album art associated with this id. So if you want to show artwork you have to insert your file in android's database and then play it from there.

Categories

Resources