Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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");
    }
        }
like image 962
Fuchsia Avatar asked Feb 12 '14 15:02

Fuchsia


3 Answers

you need to concatenate the String mFileName

mFileName = Environment.getExternalStorageDirectory().getAbsolutePath();
mFileName += "/rec" + recR  + ".mp3"; 
like image 82
Nambi Avatar answered Sep 29 '22 00:09

Nambi


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.

like image 40
Jorgesys Avatar answered Sep 29 '22 00:09

Jorgesys


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!!

like image 31
We're All Mad Here Avatar answered Sep 29 '22 01:09

We're All Mad Here