JackPowell JackPowell - 3 months ago 25
Android Question

Android MediaPlayer :: Issues

I know this is a very common question. However, I am having trouble to play the sound in my application by using MediaPlayer class despite my logic is correct. Currently, I have a shake detection features in my application. Every time the device is shaken, it should play a sound. Below is my code:

public class MainActivity extends AppCompatActivity {

private SensorManager mSensorManager;
private Sensor mAccelerometer;
private ShakeDetector mShakeDetector;
private SoundManager mSoundManager;
private TextView xText;
private Context context;
private AudioPool ap;
int id1,id2;
File directory;

MediaPlayer player, mPlayer;
AudioCollective ac;
Lagu la;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);

xText = (TextView)findViewById(R.id.xText);

mSensorManager = (SensorManager) getSystemService(Context.SENSOR_SERVICE);
mAccelerometer = mSensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER);
mShakeDetector = new ShakeDetector();

la = new Lagu();
la.initLagu(MainActivity.this);

mShakeDetector.setOnShakeListener(new ShakeDetector.OnShakeListener() {

@Override
public void onShake(int count) {

la.playLagu();
xText.setText("Shake:"+count);

}
});
}

public class Lagu {
MediaPlayer mPlayer;
public Lagu(){
mPlayer = new MediaPlayer();
}
public void initLagu(Context theContext){
mPlayer.create(theContext, R.raw.na);
}
public void playLagu(){
mPlayer.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
@Override
public void onPrepared(MediaPlayer mp) {
mp.start();
}
});
}


}

The problem is the application DOES NOT play the sound every time the phone is shaken. Not even one time the application will play the sound. FYI, the format of the song is MP3. Someone here please tell me what is going wrong with my application? Your help will be appreciated!

Answer

From the documentation for Mediaplayer.create():

Convenience method to create a MediaPlayer for a given resource id. On success, prepare() will already have been called and must not be called again.

Note: the method Mediaplayer.create() is a static method which returns a ready-to-use Mediaplayer.

So you need to assign the return value to your mPlayer You don't need any OnPreparedListener - simply call start()

public class Lagu {

MediaPlayer mPlayer;

public Lagu(){
    // do nothing or call initLagu() here
    // in this case skip the method call from the Activity's onCreate()
}

public void initLagu(Context theContext){
    mPlayer = Mediaplayer.create(theContext, R.raw.na);
}

public void playLagu(){

    mPlayer.start(); 
}

}