Search code examples
androidaudiorandomresourcesplayback

Playing random voice files upon click


I have this very basic app that has 1 button and X voice files. The voice files are in the res/ folder under raw/.

Upon tapping the button, I want the app to play a random voice file. Here's what I have so far:

Button playNasr = (Button) findViewById(R.id.button1);
    playNasr.setOnClickListener(new OnClickListener() {

        public void onClick(View arg0) {
            rand = randomGenerator.nextInt(6) + 1;
            // here's where I'm at a loss, I want to be able to concatenate
            // the random number to the "voice00" string to form
            // "voice001/2/3/etc..." in correspondence to how my voice files
            // are named.
            mp = MediaPlayer.create(Main.this, R.raw.voice00) + rand;
            mp.start();
        }
    });

Any help is appreciated, thanks in advance


Solution

  • You should try something like this:

    String voiceStr = "voice00";
    MediaPlayer mp = new MediaPlayer();
    Resources res = getResources();
    String pkgName = getPackageName();
    
    playNasr.setOnClickListener(new OnClickListener() {
        public void onClick(View v) {
            rand = randomGenerator.nextInt(6) + 1;
            // "voice00x"
            String id = voiceStr + rand;
            // Get raw resource ID
            int identifier = res.getIdentifier(id, "raw", pkgName);
            AssetFileDescriptor afd = res.openRawResourceFd(identifier);
    
            // Reuse MediaPlayer or else you will exhaust resources
            mp.reset();
            mp.setDataSource(afd.getFileDescriptor(), afd.getStartOffset(), afd.getLength();
            mp.prepare();
            mp.start();
        }
    }
    

    This way you reuse your MediaPlayer instance (and if you haven't run into errors that way yet, try hitting your button repeatedly -- you will get errors eventually) and can dynamically set the data source. You would want to optimize this to format the integer as "001", "001", etc., and be able to handle "010" as well, but I just hardcoded it for the example.