Vaibhav Kumar
Vaibhav Kumar

Reputation: 69

Audio not playing smoothly by using MediaPlayer?

I've used the following code. Audio is being played but is not smooth.

public class MainActivity extends AppCompatActivity {

    MediaPlayer mediaPlayer;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        mediaPlayer = MediaPlayer.create(getApplicationContext(), R.raw.sample);
        mediaPlayer.start();
     }

Upvotes: 1

Views: 456

Answers (2)

pleft
pleft

Reputation: 7915

Add an OnPreparedListener and start playback in the onPrepared method:

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    mediaPlayer = MediaPlayer.create(getApplicationContext(), R.raw.sample);
    mediaPlayer.setOnPreparedListener(new OnPreparedListener()
    {
        @Override
        public void onPrepared(MediaPlayer mp)
        {
            mp.start();
        }
    });
    mediaPlayer.prepare();
 }

Upvotes: 1

Shivam
Shivam

Reputation: 532

You should use mediaplayer on different thread rather then UI thread. It will play smooth then.

Upvotes: 0

Related Questions