Chance
Chance

Reputation: 135

Android Loading & Playing Sound Based on String

I'm currently working on a simple Android app, and right now I am trying to get it to load in and play sounds. The problem I am faced with is that I want the sound it uses to be based on a string (With the same name as the sound file). The reason for this is simplicity in both the code and adding on to it.

Now unfortunately I can't just slap a string in place of referencing the actual sound, but is there some way for me to compare a string to the entire raw folder to find the matching sound, or some other alternative short of defining every sound manually?

Thank you for your time.

Upvotes: 0

Views: 1268

Answers (3)

Emile
Emile

Reputation: 11721

This page explains how to use getresources().getidentifier().

Upvotes: 1

GSree
GSree

Reputation: 2898

Try using Reflection package to check if the file exists.

snippet

    try {
        Class res = R.raw.class;
        Field field = res.getField(<yourmediafile>);
        //If the code reach here, that means media file exists.
    } catch (Exception e) {
        //No media file with that name
    }

Upvotes: 0

Stevy888
Stevy888

Reputation: 364

Why do you need to do this? if the files are already in the raw file, and your looking to simply have the strong be the name of the file, then any amount of coding to do this would probably take longer then simply referencing the file since the reference would just be:

R.raw.file_name

instead of:

file_name

Thats not a lot more typing, especially if its a simple app.

Upvotes: 0

Related Questions