Fuchsia
Fuchsia

Reputation: 77

Play audio button is not working

I have a layout in which there's a 'Listen' button, so that if I press it, it will play certain audios by random (they have been assigned ids, but let's not worry about that) in my phone. However, when I click on the button, nothing plays, although the toast shows up with the correct filename.

Can someone please take a look and tell me what's wrong with my code? Thanks! >_<

Button btnListen= (Button) findViewById(R.id.buttonListen);
String recR = getIntent().getStringExtra("dataR"); //importing random filename
mFileName = Environment.getExternalStorageDirectory().getAbsolutePath();
mFileName = "/rec" + recR  + ".mp3"; 
//filename starts with rec, so itll usually be like recwoof.mp3 or rectest.mp3 etc

btnListen.setOnClickListener(new OnClickListener(){

@Override

public void onClick(View v) {
MediaPlayer mPlayer = new MediaPlayer();
Toast.makeText(getApplicationContext(), "show "+ mFileName + " now",
Toast.LENGTH_LONG).show();
    try {
     mPlayer.setDataSource(mFileName);
         mPlayer.prepare();
         mPlayer.start();
    } catch (IOException e) {
    Log.e("meh log", "prepare() failed");
    }
        }

Upvotes: 5

Views: 115

Answers (3)

Jorgesys
Jorgesys

Reputation: 126455

I think the problem is here:

mFileName = Environment.getExternalStorageDirectory().getAbsolutePath();
mFileName = "/rec" + recR  + ".mp3"; 

change to:

mFileName = Environment.getExternalStorageDirectory().getAbsolutePath() + "/rec" + recR  + ".mp3"; 

You will get more info in LogCat

Change this :

 } catch (IOException e) {
    Log.e("meh log", "prepare() failed");
 }

to:

 } catch (IOException e) {
    Log.e("Fuchsia Player", e.getMessage());
 }

So in your LogCat you can find the tag "Fuchsia Player" and more info about the exception.

Upvotes: 3

We&#39;re All Mad Here
We&#39;re All Mad Here

Reputation: 1554

Consider taking a look here: Android player He provides a throughout tutorial with the code how to create a music player, with of course the button that you are asking!!

Upvotes: 2

Nambi
Nambi

Reputation: 12042

you need to concatenate the String mFileName

mFileName = Environment.getExternalStorageDirectory().getAbsolutePath();
mFileName += "/rec" + recR  + ".mp3"; 

Upvotes: 3

Related Questions