Apython
Apython

Reputation: 453

how to play an audio file based on a string variable on Android

so I'm building an interface on Android, where the user enters a word and then IF the word exists in the databank, then a button appears and when the user clicks on it "OnClick= buttonClicked" - the sound is played.

There are lots of examples that deal with a specific string names as parameters for the MediaPlayer, but I haven't seen any yet that deals with a string variable instead.

Here is what I mean:

If you want to play this specific audio that plays an airplane sound. You would create a method that handles the button click like that:

//play airplance.mp3 inside of res/raw:

public void buttonClicked(View view) {

  MediaPlayer mp = MediaPlayer.create(this,  R.raw.airplane);
  mp.start();
 }

that works.

now, if instead of specifying the String name, i'd like to use a String variable myInput:

EditText editText = (EditText) findViewById(R.id.input); 
String myInput = editText.getText().toString();

how should I define it in the media player? cause the following doesn't work:

public void buttonClicked(View view) {

   MediaPlayer mp = MediaPlayer.create(this,  R.raw.myInput);
   mp.start();

}

I also tried by using getResources().getIdentifier():

public void buttonClicked(View view) {

int resID=getResources().getIdentifier(myInput, "raw",    this.getPackageName());

 MediaPlayer mp = MediaPlayer.create(this, resID);
    mp.start(); 

}

but also here the app crashes!

anybody can help? would very much appreciate that!

Upvotes: 0

Views: 1309

Answers (1)

Apython
Apython

Reputation: 453

After long struggle I finally found the answer.

If myInput is the variable, then it is possible to use a String of the path , parse it to Uri and finally pass it into create(). I also used try-catch because I noticed that if the file is not found in the folder, then the app crashes. Here is the solution that worked for me:

    String uriPath = "android.resource://" + getPackageName() + "/raw/" + myInput;
    Uri uri = Uri.parse(uriPath);
    mp = MediaPlayer.create(this, uri);
    try {
        mp.start();
    }
    catch (Exception e) {}

Upvotes: 1

Related Questions