ruhalde
ruhalde

Reputation: 3551

Android, accessing internal sound files as resource IDs

I need to send some feedback to user by playing a click sound. I'm trying to use MediaPlayer.create () with built in OGG sound files, mainly KeypressStandard.ogg.

How do I refer to these files as resource IDs?

Upvotes: 1

Views: 4444

Answers (3)

Thomio
Thomio

Reputation: 1433

If you want to use your device resources you can get them without hard-coding, using RingtoneManager or ToneGenerator.

Uri sound_uri = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION)

You can also look for free audio files on the web. Check this: https://rcptones.com/dev_tones/

Upvotes: 0

ruhalde
ruhalde

Reputation: 3551

For anybody interested in this question, found a solution like this:

MediaPlayer mp = MediaPlayer.create(getApplicationContext(), Uri.parse("/system/media/audio/ui/Effect_Tick.ogg") );
mp.start();

I fired this inside an AsyncTask where I do my visual feedback chores, in onPreExecute() I draw "selected" state, play click sound and wait for 300mS. in onPostExecute(), I redraw object and free resources, works very nice, sample code:

private class FeedbackHandler extends AsyncTask<Void,Void,Void>{
    MediaPlayer mp;

    @Override
    protected Void doInBackground(Void... arg0) {
    return null;

    }

    @Override
    protected void onPostExecute(Void result) {
    super.onPostExecute(result);

    mp.release(); // free resources
    mp=null; // help GC
    myDrawUnselectedState(myObject); // draw normal state
    ImageView iv = (ImageView) findViewById(R.id.myobjectcontainer);
    iv.invalidate(); // mark UI for refresh
    }

    @Override
    protected void onPreExecute() {
    super.onPreExecute();

    myDrawSelectedState(myObject); // draw selected
    ImageView iv = (ImageView) findViewById(R.id.mycontainer);
    iv.invalidate(); // mark for refreshing
    mp = MediaPlayer.create(getApplicationContext(), Uri.parse("/system/media/audio/ui/Effect_Tick.ogg") );
    mp.start(); // play sound
    SystemClock.sleep(300); // wait a little bit for user to see effect
    }       
}

By the way, Effect_Tick.ogg its the one that fires when you press a button. It seems that these file names are pretty much Android standard, found in many different devices signed with Android copyright disclaimer.

Upvotes: 2

Augusto
Augusto

Reputation: 29867

The files should be in the raw folder and you can refer to it by id with R.raw.KeypressStandard

Upvotes: 3

Related Questions