Play a random sound on a button click - android

I wonder if you could help. Im trying to play a random sound (from a set of 7 available sounds) when a user clicks on a button. So far I have:
Random rand = new Random();
int rndm = rand.nextInt(6) + 1; // I have 7 random sounds to play sequentially named 'my sound' + n.
String sndName = "mysound" + rndm; // Assign a random # to the end of the sound file.
mp1 = MediaPlayer.create(getApplicationContext(), R.raw.sndName); // ERROR HERE: Expects an Int
mp1.start();
My hope was that one of my sound files (mysound1, mysound2, mysound3,...) would play randomly but eclipse complains that the mp1 assignment is expecting an int. Any ideas?
Thanks much.

Use
int[] sounds={R.raw.mysound1, R.raw.mysound2, R.raw.mysound3,R.raw.mysound4,R.raw.mysound5,R.raw.mysound6,R.raw.mysound7};
Then
Random r = new Random();
int Low = 0;
int High = 7;
int rndm = r.nextInt(High-Low) + Low;
mp1 = MediaPlayer.create(getApplicationContext(),sounds[rndm]);
mp1.start();

The issue is that you need to get the resource id to pass in. You'll need to use something like this.
int id = getResources().getIdentifier("mysound" + rndm, "raw", getApplicationInfo().packageName);
mp1 = MediaPlayer.create(getApplicationContext(), id);

Two things. First I recommend you look at the line above where you create the string. If I remember correctly you may need to use a function such as to String to get the integer to be a string to concatenate on your string.
Next, I don't believe the r.raw is going to work like that.
My recommendation is if you have only 7 items, make an array holding the resources.
int [] resources = {R.raw.mysound1, R.raw.mysound2} etc
Then use the index from before to select the right R file.
So in the media create line, replace R.raw.sndName with resources[rndm]

your program using variable error. see below code:
// 1. R.raw.sndName is Constant
mp1 = MediaPlayer.create(getApplicationContext(), R.raw.sndName);
// 2. android resource must integer, Starting from this idea

Related

Array of methods

I am trying to randomly call methods to make it use a different animation every time to display a textview. I trie using an array but not sure how to implement it. My array looks like this (obviously I know it shouldn't be strings but not sure what data type or if even possible this way).
String [] mAnimations = {"Hinge","RollIn", "Landing",
"BounceIn", "BounceInDown", "BounceInLeft", "BounceInRight",
"BounceInUp", "FadeIn", "FadeInUp", "FadeInDown", "FadeInLeft",
"FadeInRight","FlipInX", "RotateIn", "RotateInDownLeft", "RotateInDownRight",
"RotateInUpLeft", "RotateInUpRight", "SlideInLeft", "SlideInRight",
"SlideInUp", "SlideInDown", "ZoomIn", "ZoomInDown", "ZoomInLeft",
"ZoomInRight", "ZoomInUp"};
Putting any of the correct animations by themselves it works fine (Note BounceInLeft):
YoYo.with(Techniques.BounceInLeft)
.duration(1000)
.playOn(textView);
But what I am trying to do is randomly pick an animation from the array something like this:
Random rand = new Random();
int n = rand.nextInt(mAnimations.length) + 1;
YoYo.with(Techniques.(mAnimations[n]))
.duration(1000)
.playOn(textView);
Thanks for your help
Nicholas
Best Directly Assign method based on Random numbers.Because (mAnimations[n]) value consider as String.
String [] mAnimations = {"Hinge","RollIn", "Landing",
"BounceIn", "BounceInDown", "BounceInLeft", "BounceInRight",
"BounceInUp", "FadeIn", "FadeInUp", "FadeInDown", "FadeInLeft",
"FadeInRight","FlipInX", "RotateIn", "RotateInDownLeft", "RotateInDownRight",
"RotateInUpLeft", "RotateInUpRight", "SlideInLeft", "SlideInRight",
"SlideInUp", "SlideInDown", "ZoomIn", "ZoomInDown", "ZoomInLeft",
"ZoomInRight", "ZoomInUp"};
Random rand = new Random();
int n = rand.nextInt(mAnimations.length);
if(n==0)
{
YoYo.with(Techniques.Hinge).duration(1000).playOn(textView);
}
if(n==1)
{
YoYo.with(Techniques.RollIn).duration(1000).playOn(textView);
}

How to call resources with string name in android?

I'm now trying to call the resources( in my application they are mp3 files and images).
For the mp3 file part, my code goes like this ( not working obviously!)
if(i==1)
{
hoho= MediaPlayer.create(getApplicationContext(), R.raw.univ_day1);
hoho.start();
}
else if (i==2)
{
hoho= MediaPlayer.create(getApplicationContext(), R.raw.univ_day2);
hoho.start();
}
...
In my application, there are hundreds of mp3 file inside the application. So what I want to do is briefly summarize code into something like this.
hoho=MediaPlayer.crate(getApplicationContet(), R.raw.univ_day+"i"); //This also looks really awkward.
If I knew how to write down code just like above one. How can I handle the name of raw files and the form like "R.raw...."? If I can do, then I also can apply similar approach to the image resources.
You can get resource id by its name using public int getIdentifier (String name, String defType, String defPackage) method.
For example:
int id = getResources().getIdentifier("univ_day"+i, "raw", getPackageName());
hoho = MediaPlayer.create(getApplicationContext(), id);
We can list all the names of raw assets, which are basically the filenames without the extensions, we can do this as -
public void listRaw(){
Field[] fields=R.raw.class.getFields();
for(int count=0; count < fields.length; count++){
Log.i("Raw Asset: ", fields[count].getName());
}
}
Next you'll need to refer to them by the integer assigned to that resource name. You can get this integer as:
int resourceID=fields[count].getInt(fields[count]);
This is the same int which you'd get by referring to R.raw.yourRawFileName.
In your code you can use this like -
hoho= MediaPlayer.create(getApplicationContext(), resourceID);
hoho.start();
Next you can apply JAVA logic to play previous current and next media files. Please let know if you need help here also.

Using a Random Number in a Drawable Path

I am using a random number to set my imageButton to a random image. I am wondering if there is a way to use the random int in the file path for the drawable. This code gives a run time error for invalid integer but will compile.
Random generator = new Random();
int chooseFirstPicture = generator.nextInt(2);
int imagePath1 = Integer.parseInt("R.drawable.image" + chooseFirstPicture);
btn1.setBackgroundResource(imagePath1);
You are parsing a String to a Integer, so your code is going to throw a NumberFormatException every time you run it.
The correct way to get a resource id from a String key is using the function getIdentifier():
Random generator = new Random();
int chooseFirstPicture = generator.nextInt(2);
int resourceId = getResources().getIdentifier("image" + chooseFirstPicture, "drawable", getPackageName());
if (resourceId != 0) {
//Provided resource id exists in "drawable" folder
btn1.setBackgroundResource(imagePath1);
} else {
//Provided resource id is not in "drawable" folder.
//You can set a default image or keep the previous one.
}
You can find more information in the Android Resources class documentation.
Hm.. You trying to convert "R.drawable.image1" string to an integer that is impossible. During compilation nothing checks what's in the string, but when you run the app, it fails immediately.
Better to use the getResources().getIdentifier() with proper parameters (link)
I hope it helps :)

Get random sound file from raw folder - Android - MediaPlayer

I'd like to:
Generate a random number (easy enough)
take that random number and add it to some sort of dynamic path
use the dynamic path in the mediaplayer creation.
E.g.
Resource folder(raw) contains
1.mp3
2.mp3
3.mp3
Random number generates a number between 0 and 4
e.g: 2
Inserts random number to path
E.g. a String?
String PATH = "R.raw." + RANDOM-NUMBER
MediaPlayer mp = MediaPlayer.create(context, PATH);
However, of course MediaPlayer uses a URI variable not a string, i did try
myUri = Uri.parse("R.raw.2");
but get a nullPointerException
I imagine this is very simple/straight forward to answer and my knowledge simply evades me
Thanks very much
You cant do that with resources. Here's how I see you'd go about it.
int randomInt = generateRandomInt(), id;
switch (randomInt) {
case 1:
id = R.raw.1;
break;
case 2:
id = R.raw.2;
break;
...
}
setDataFromResource(getResources(), myMediaPlayer, id);
AFAIK, you have to use setDataFromResource to set the data for your media player from R.raw
Personally I would do it like this:
//initializing the sounds
final MediaPlayer sound1 = MediaPlayer.create(this, R.raw.1);
final MediaPlayer sound2 = MediaPlayer.create(this, R.raw.2);
final MediaPlayer sound3 = MediaPlayer.create(this, R.raw.3);
//generate random number
Random randomGenerator = new Random();
int randomInt = randomGenerator.nextInt(3) + 1;
//picking the right sound to play
switch (randomInt){
case 1: sound1.start();
break;
case 2: sound2.start();
break;
case 3: sound3.start();
break;
}

How to refer to a random integer in R.raw method in Android?

I have this code
Random x = new Random(44);
int l = x.nextInt();
int path = R.raw.l;
I know it doesn't work that way,but it explains my situation the most.
i.e. Providing l==5, i want to use R.raw.5 as the path. however, R.raw seems to understand only straightforward values, not the referred ones.
Please help!
You can get int indentifier from your activity with this code:
Random x = new Random(44);
int l = x.nextInt();
int path = getResources().getIdentifier(String.valueOf(l), "raw", getPackageName());
More info in documentation: http://developer.android.com/reference/android/content/res/Resources.html#getIdentifier%28java.lang.String,%20java.lang.String,%20java.lang.String%29

Categories

Resources