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;
}
Related
I'm working on an application, where for specific choosen items, specific .mp3 should be assigned. (Like I choose Dachshund, then I dachshund_1.mp3, dachshund_2.mp3 etc. to be played when my functions say so). Is it possible somehow, that I create a variable, that holds the specific name, then I assign it to mediaplayer.create?
What I would like to do would look like that below:
// I have a function here that returns with the specific string
// I have a cnt variable in the code which helps determine which text and sound comes now
fun DogHandler(cnt:Int, receiptName: String) :String
{
return dogName + "_" +cnt.toString()
}
This function is called, and the string it returns should go to the mediaplayer. Cnt is let's say 10
var tmp = DogHandler(dachshund, cnt); // tmp = dachsund_10
mediaPlayer = MediaPlayer.create(context, R.raw.tmp)
mediaPlayer.start()
To my knowledge there is no way to generate resource IDs (like R.raw.something) dynamically. However, you could simply create a list of them and access it by index.
val dachsunds = listOf(
R.raw.dachsund_0,
R.raw.dachsund_1,
R.raw.dachsund_2,
R.raw.dachsund_3,
// ...
R.raw.dachsund_10
)
val dachsund = dachsunds[dachsundIndex]
val mediaPlayer = MediaPlayer.create(context, dachsund).apply {
start()
}
I'm developing currently an IME, and I have sound for button click. I have an option in the preferences screen to change the volume of the sounds. The SeekBar values are going from 0.0 to 1.0. Now I try to let the user to configure the volume of the buttons in the preferences screen and later I get this value and save it as mSoundVol parameter. So for the sound of the click I wrote the following method:
float soundVolume;
int maxVolume, sound;
switch (primaryCode) {
case Keyboard.KEYCODE_DELETE:
maxVolume = mAudioManager.getStreamMaxVolume(mAudioManager.FX_KEYPRESS_DELETE);
sound = mAudioManager.FX_KEYPRESS_DELETE;
Log.d(TAG+ "-volume", "chosen sound: mAudioManager.FX_KEYPRESS_DELETE");
break;
case ASCII_ENTER:
maxVolume = mAudioManager.getStreamMaxVolume(mAudioManager.FX_KEYPRESS_RETURN);
sound = mAudioManager.FX_KEYPRESS_RETURN;
Log.d(TAG+ "-volume", "chosen sound: mAudioManager.FX_KEYPRESS_RETURN");
break;
case ASCII_SPACE:
maxVolume = mAudioManager.getStreamMaxVolume(mAudioManager.FX_KEYPRESS_SPACEBAR);
sound = mAudioManager.FX_KEYPRESS_SPACEBAR;
Log.d(TAG+ "-volume", "chosen sound: mAudioManager.FX_KEYPRESS_SPACEBAR");
break;
default:
maxVolume = mAudioManager.getStreamMaxVolume(mAudioManager.FX_KEYPRESS_STANDARD);
sound = mAudioManager.FX_KEYPRESS_STANDARD;
Log.d(TAG + "-volume", "chosen sound: mAudioManager.FX_KEYPRESS_STANDARD");
}
soundVolume = maxVolume * mSoundVol;
Log.d(TAG+ "-volume", "current max volume: " + maxVolume + " current volume setting: " +mSoundVol * 100 +"%" + " volume result: " + soundVolume);
mAudioManager.playSoundEffect(sound, soundVolume);
But for some reason this does not change the volume of the sound for the user.
Can some one tell me what am I doing wrong with the AudioManager here?
Thanks.
your need to use this method for a more accurate result
AudioManager audioManager =
(AudioManager)getSystemService(Context.AUDIO_SERVICE);
audioManager.setStreamVolume(AudioManager.STREAM_MUSIC,
[int value],
[if desired a flag]);
EDIT
Take this FLAg as example
AudioManager.FLAG_PLAY_SOUND
This means that whenever the user press the volume Button a bip will be outputed
EDIT 2
here is an implementation of the code
audioManager.setStreamVolume(AudioManager.STREAM_MUSIC,
AudioManager.getStreamMaxVolume(),
AudioManager.FLAG_PLAY_SOUND);
The solution in my case was this:
float soundVolume;
int maxVolume, sound;
switch (primaryCode) {
case Keyboard.KEYCODE_DELETE:
sound = mAudioManager.FX_KEYPRESS_DELETE;
break;
case ASCII_ENTER:
sound = mAudioManager.FX_KEYPRESS_RETURN;
break;
case ASCII_SPACE:
sound = mAudioManager.FX_KEYPRESS_SPACEBAR;
break;
default:
sound = mAudioManager.FX_KEYPRESS_STANDARD;
break;
}
maxVolume = mAudioManager.getStreamMaxVolume(AudioManager.STREAM_MUSIC);
soundVolume = maxVolume * mSoundVol;
mAudioManager.setStreamVolume(AudioManager.STREAM_SYSTEM , (int)(soundVolume * 1.5) , 0);
mAudioManager.playSoundEffect(sound);
The important thing was to pass 0 as the last parameter of the setStreamVolume method, that way this action only changes the volume without playing any other sound of showing the volume UI.
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.
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
How can I display back to the user a basic popup with a saying based on a random number generated. I wanted to use a switch statement, but that just displays all the sayings, ie:
int random = (int) Math.ceil(Math.random() * 5);
switch(random){
case 1:
showToast(this, "Saying 1.");
case 2:
showToast(this, "Saying 2.");
}
etc....
Like I said, this displays all 5 case statements, is there a better way to random generate and display based on the number, or am I doing it all wrong?
Thanks!
The case statements inside a switch "fall through" if you don't break out of them.
It should be like this:
switch(random) {
case 1:
statement;
break;
case 2:
statement;
break;
...
}
The break statement jumps to the next line after the switch statement.
You can also try some thing like
String[] sayings = {"Saying 1.", "Saying 2.", "Saying 3.", "Saying 4.", "Saying 5."};
int random = (int) Math.ceil(Math.random() * 5);
showToast(this, sayings[random]);
and if you have more items then you can prepare the string array dynamically before use.
If there are many sayings... you can also put a .txt file in your assets folder with numerous sayings (one per line), read it and display the saying from a randomly generated line number..
Activity.getAssets().open("sayingsfile.txt");