Issue
For a little game I'm programming I'm trying to supply the user with some voice lines for flavor reasons. I've already recorded several lines, and they're all in the format of languageCode_packageName_name01.mp3
.
Since I don't want the same few lines to play all the time, I intend to record several versions, and randomly pick one when retrieving them. For example, retrieving lines for "start" two times could result in playback of de_std_start01
and then de_std_start06
.
Since I am quite new to android I'd like to ask for help regarding this implementation. I'm not sure whether I should utilize the raw folder for this task, or the assets folder. If possible, I would like to implement a folder structure like this, which would to my understanding need the use of the assets folder, in order to be able to simply drag & drop new files inside the folder, which will then be taken into account for random selection.:
<root folder>
- de
-- std
--- start
---- start01.mp3
---- start02.mp3
...
When given arguments specifying de
, std
and start
, how would I go about retrieving the different files and randomly pick one of them? Thanks for your help!
Solution
If you include them in the raw folder, you should be able to access them as so:
//from your activity
AudioService audioService = new AudioService;
int randomTune = audioService.getRandom();
MediaPlayer mediaPlayer = MediaPlayer.create(context, randomTune);
mediaplayer.start;
//From a seperate service class
Class AudioService {
private int[] audioFiles = {
R.raw.song1, R.raw.song2, R.raw.song3, R.raw.song4, R.raw.song5, R.raw.song6
};
I believe that your folder structure will be somewhat flexible since you are wrapping the actual resource with the R class and referencing that in your code.
public int getRandom(){
// Here i am asking for a random number between 0 and 1, multiplying by 6, rounding
// it down, and explicitly casting to int.
// Result will be random int between 0 and 5. This will be the array index that
// randomly chooses the song.
private int randomIndex;
randomindex = (int) Math.floor(6 * Math.random);
return this.audioFiles[randomIndex];
}
}
Answered By - Nate T
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.