String to resources path converter - android

I can't find in my books if there is way to convert string to resources path in android development.
For example:
String path = "R.raw.mediaFile";
MediaPlayer myPlayer;
myPlayer = MediaPlayer.create(this, ***<Some Expression>(path)***);
Please provide a short example.
Thanks in advance!

I think you're after
context.getResources().getIndentifier(...)
Converts a String reference to the int value. See here http://developer.android.com/reference/android/content/res/Resources.html#getIdentifier%28java.lang.String,%20java.lang.String,%20java.lang.String%29
Another useful method once you've got the id is
AssetFileDescriptor afd = context.getResources().openRawResourceFd(resid);
You can set this as a datasource for the media player
myPlayer.setDatasource(aft.getFileDescriptor())

Related

Using multiple audio sources for a media player in Android Studio

I want to create a media player with multiple sounds and play one at random when a button is clicked.
I tried using the MediaPlayer.create() function but I can only set one audio source.
I also tried using the setDataSource() function but this only seems to work for resources that are stored outside the application (as far as I know).
String meowsounds[] = new String[]{
"R.raw.meowcat1",
"R.raw.meowcat2",
"R.raw.meowcat3",
"R.raw.meowcat4",
"R.raw.meowcat5",
};
MediaPlayer mp = new MediaPlayer();
meow.setOnClickListener((view) ->{
Random random = new Random();
int r = random.nextInt(6-1) + 1;
try{
mp.setDataSource(meowsounds[r]);
mp.prepare();
mp.start();
}catch(Exception e){e.printStackTrace();}
});
This code doesn't give any error while running but doesn't play anything on click
EDIT: Updated code which works on first click but not on subsequent clicks:
meow.setOnClickListener((view) ->{
Random random = new Random();
int r = random.nextInt(6-1) + 1;
Toast.makeText(MainActivity.this,Integer.valueOf(r).toString(),Toast.LENGTH_SHORT).show();
try{
if(r==1)
fileDescriptor = MainActivity.this.getResources().openRawResourceFd(R.raw.meowcat1);
else if (r==2)
fileDescriptor = MainActivity.this.getResources().openRawResourceFd(R.raw.meowcat2);
else if (r==3)
fileDescriptor = MainActivity.this.getResources().openRawResourceFd(R.raw.meowcat3);
else if (r==4)
fileDescriptor = MainActivity.this.getResources().openRawResourceFd(R.raw.meowcat4);
else
fileDescriptor = MainActivity.this.getResources().openRawResourceFd(R.raw.meowcat5);
mp.setDataSource(fileDescriptor.getFileDescriptor(), fileDescriptor.getStartOffset(), fileDescriptor.getLength());
mp.prepare();
mp.start();
}catch(Exception e){e.printStackTrace();}
});
R - is the class with constants. "R.raw.meowcat1" - is the simple string and it is not constant which consider link to file.
First, you need to create int array of raw constants, but not string array of simple strings.
Second, If you want to play file from raw, you need to create AssetFileDescriptor for this raw file and use in setDataSource method. For example:
AssetFileDescriptor fileDescriptor = getContext().getResources().openRawResourceFd(R.raw.meowcat1);
mediaPlayer.setDataSource(fileDescriptor.getFileDescriptor(), fileDescriptor.getStartOffset(), fileDescriptor.getLength());
And don't forget please release codec in onDestroy method.

How to give android MediaPlayer a String Path?

I wrote a Media Player in my app and wrote this code below:
mediaPlayer = MediaPlayer.create(this, R.raw.file);
I want to give my mediaplayer this String path instead of a uri:
String path = "http://example.org/file.mp3";
How can I do that?
Guys Please answer my question with some code!!!
Thank you so much!
Uri uri = Uri.parse("http://example.org/file.mp3");
player = new MediaPlayer();
player.setDataSource(context, uri);
player.start();

Read mp3 metadata from assets folder

I have an app with some mp3 files stored inside a subfolder of assets folder.
I obtain list of files in this way
context.getAssets().list("audio");
and results show it inside a listview.
By doing this, what i see is a list of mp3 filenames. Now i don't want show filenames, but associated metadata for each file.
Copying the file to disk isn't necessary. MediaMetadataRetriever and FFmpegMediaMetadataRetriever both offer a setDataSource method that takes a FileDescriptor as an argument:
FFmpegMediaMetadataRetriever metaRetriver = new FFmpegMediaMetadataRetriever();\
// or MediaMetadataRetriever metaRetriver = new MediaMetadataRetriever();
String path = "audio";
String [] files = context.getAssets().list(path);
for (int i = 0; i < files.length; i++) {
String file = path + "/" + files[i];
AssetFileDescriptor afd = context.getAssets().openFd(file);
metaRetriver.setDataSource(afd.getFileDescriptor(), afd.getStartOffset(), afd.getLength());
String album = metaRetriver.extractMetadata(FFmpegMediaMetadataRetriever.METADATA_KEY_ALBUM);
String artist = metaRetriver.extractMetadata(FFmpegMediaMetadataRetriever.METADATA_KEY_ARTIST);
String gener = metaRetriver.extractMetadata(FFmpegMediaMetadataRetriever.METADATA_KEY_GENRE);
afd.close();
}
metaRetriver.release();
Here you go.
First get the file path as shown here
How to pass a file path which is in assets folder to File(String path)?
And then get metadata of audio as shown here
How to extract metadata from mp3?
By metadata means name, title, time etc data if you want then you need to use MediaMetadataRetriever class to do so..
MediaMetadataRetriever metaRetriver = new MediaMetadataRetriever();
metaRetriver.setDataSource("path of song");
String album = metaRetriver.extractMetadata(MediaMetadataRetriever.METADATA_KEY_ALBUM);
String artist = metaRetriver
.extractMetadata(MediaMetadataRetriever.METADATA_KEY_ARTIST);
String gener=metaRetriver
.extractMetadata(MediaMetadataRetriever.METADATA_KEY_GENRE);
Similarly you can extract other data also..
Hope it will help you.

Play a file from the raw folder using Android mediaPlayer, using its resourceId

In Android, I can use MediaPlayer.create(context, R.raw.myFileName) to create an instance of the mediaPlayer, using a resource from the raw/ folder, and I can then use .start() to get that file to play. Later, I can use the various signatures for .setDataSource() to change the file that I want to play.
I can obtain the resourceId for a given file in the raw/ folder, using:
int resourceId = activity.getResources().getIdentifier("myFileName", "raw", activity.getPackageName());
Is it possible to use this integer resourceId to start playing that file instead of the current one? Or do I have to determine the full path to the file res/raw/myFileName.mid in order to change the track?
I am hoping that the solution will be something like this, with a real method instead of my invented equivalentToSetDataSourceUsingAResourceId() method name.
Resources resources = activity.getResources();
String packageName = activity.getPackageName();
int white = resources.getIdentifier("white", "raw", packageName);
int black = resources.getIdentifier("black", "raw", packageName);
MediaPlayer mediaPlayer = MediaPlayer.create(activity, white);
mediaPlayer.start();
// ... and some time later...
mediaPlayer.reset();
mediaPlayer.equivalentToSetDataSourceUsingAResourceId(black);
mediaPlayer.prepare();
mediaPlayer.start();
An alternative would be to destroy the current mediaPlayer instance and create a new one each time the sound file needs to change:
if (mediaPlayer != null) {
mediaPlayer.stop();
mediaPlayer.release();
mediaPlayer = null;
}
mediaPlayer = MediaPlayer.create(activity, black);
mediaPlayer.start();
This does not seem elegant to me.
According to MediaPlayer documentation setDataSource API's allowed only on fresh instance (IDLE state) of MediaPlayer. Which means you have to release() and recreate MediaPlayer from scratch if you wanna use only one instance at time.
Try do like this. Just pass id of your raw resource:
mMediaPlayer = MediaPlayer.create(this, R.raw.whatever);

How to play a recorded audio file?

I'm using MediaRecorder class to record an audio file and I used
final String MEDIA_OUTPUT_FILE = "MyOutPutFile";
mediaRecorder.setOutputFile(MEDIA_OUTPUT_FILE);'
to give a name to my output file.
I also know how to Play an Audio File from Resources:
MediaPlayer mpRes = MediaPlayer.create(getApplicationContext(), R.raw.audiofile);
mpRes.start();'
My Question Is, Now, how to play the recorded file while I dont know where my MEDIA_OUTPUT_FILE is saved?
Instead of using constant as argument for mediaRecorder.setOutputFile() use a variable like below.
private String filePath;
filePath = Environment.getExternalStorageDirectory().getAbsolutePath();
filePath += "/myrecording.mpeg";
Then pass the filePath variable as the argument as follow;
mediaRecorder.setOutputFile(filePath);
Then you can play the recorded file as follows;
mediaPlayer = new MediaPlayer();
mediaPlayer.setDataSource(filePath);
mediaPlayer.start();
That's it.

Categories

Resources