Search code examples
javaandroidandroid-studioandroid-mediaplayer

Problem in playing audio file using media player


Here is the code for the button which should start and pause the audio. I have checked the button-text == "start" or "pause" and change the text and use the appropriate methods accordingly i.e mediaplayer.start() and mediaplayer.pause(). But still, the audio won't play.

package com.example.demo;

import android.media.MediaPlayer;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;


public class MainActivity extends AppCompatActivity 

{
MediaPlayer mediaPlayer;//Mediaplayer
Button button;
public void start(View view)
{
    String text = button.getText().toString();
    if (text == "start") 
    {
        mediaPlayer.start(); //starting the audio
        button.setText("pause");
    } 
    else 
    {
        mediaPlayer.pause(); //pausing the audio
        button.setText("start");
    }
}

@Override
protected void onCreate(Bundle savedInstanceState) 
{
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    button =  findViewById(R.id.start);
    mediaPlayer =  MediaPlayer.create(this,R.raw.music);
}
}

Solution

  • There are a few steps you should try: First, try this because I think It gives always a false condition:

    if(text.trim().equals("start"))
    

    If Still not work Try this one:

        public class MainActivity extends AppCompatActivity 
    
        {
        MediaPlayer mediaPlayer;//Mediaplayer
        Button button;
    
    
        @Override
        protected void onCreate(Bundle savedInstanceState) 
        {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_main);
            button =  findViewById(R.id.start);
            mediaPlayer =  MediaPlayer.create(this,R.raw.music);
            button.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
    
            String text = button.getText().toString().trim();
            if (text.equals("start")) 
            {
                mediaPlayer.start(); 
                button.setText("pause");
            } 
            else 
            {
                mediaPlayer.pause(); 
                button.setText("start");
            }
    
          }
        }
    } }