Kris Kris - 2 months ago 15
Android Question

Android: Play mp3 file from raw resource on click of a TextView

Hi guys I want to play a certain mp3 file when a text is clicked. For example, I clicked the word "Nicholas", the app have to play nicholas.mp3...

Sorry for my messy code, I'm new to android dev:

package com.example.playword;

import java.io.IOException;

import android.app.Activity;
import android.media.MediaPlayer;
import android.os.Bundle;
//import android.os.Handler;
import android.view.View;
//import android.view.View.OnClickListener;
//import android.widget.Button;
import android.widget.TextView;

public class PlayWord extends Activity {
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);

//final Handler mHandler = new Handler();

final TextView nicholas = (TextView) findViewById(R.id.nicholas);
final TextView was = (TextView) findViewById(R.id.was);

nicholas.setText("Nicholas ");
was.setText("was ");

/*
Button btn = (Button) (findViewById(R.id.nicholasBtn));

btn.setOnClickListener(new OnClickListener(){
@Override
public void onClick(View v) {
nicholas.setText("Nicholas (Clicked!) ");
}

});
*/

View.OnClickListener handler = new View.OnClickListener(){
public void onClick(View v) {
switch (v.getId()) {
case R.id.nicholas: // doStuff

MediaPlayer mPlayer = MediaPlayer.create(null, R.raw.aaanicholas);

try {
mPlayer.prepare();
} catch (IllegalStateException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}

mPlayer.start();

nicholas.setText("Nicholas (Clicked!) ");
break;

case R.id.was: // doStuff

MediaPlayer mPlayer1 = MediaPlayer.create(null, R.raw.aaawas);

try {
mPlayer1.prepare();
} catch (IllegalStateException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}

mPlayer1.start();

was.setText("was (Clicked!) ");
break;
}
}
};

findViewById(R.id.nicholas).setOnClickListener(handler);
findViewById(R.id.was).setOnClickListener(handler);

}
}


When I run this, I'm getting a force close error.. Do you have a much better idea on this? Many thanks in advance!

Answer

You need to pass in a context instance into MediaPlayer.create method:

MediaPlayer mPlayer = MediaPlayer.create(PlayWorld.this, R.raw.aaanicholas);

Also, after the create() call, prepare is already executed, so you don't need to execute it explicitly, just invoke start() right after create().