Android Studio : MediaPlayer setDataSource URL not playing music

Solution for Android Studio : MediaPlayer setDataSource URL not playing music
is Given Below:

Opening app without any error. But can’t play music. But can play music from local machine. Internet connection is fine.

I have enabled internet permission in AndroidManiFest.xml

<uses-permission android:name="android.permission.INTERNET" />

I have enabled http permission.

android:usesCleartextTraffic="true"

MediaPlayer mediaPlayer = new MediaPlayer();
try {
        mediaPlayer.setDataSource("http://penguinradio.dominican.edu/Sound%20FX%20Collection/Motorbike.mp3");
    } catch (IOException e) {
        e.printStackTrace();
}

mediaPlayer.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
            @Override
            public void onPrepared(MediaPlayer mP) {
                Toast.makeText(MainActivity.this, "Ready to Play", Toast.LENGTH_SHORT).show();
                mP.start();
            }
        });
mediaPlayer.prepareAsync();

Full Code:
https://paste.ubuntu.com/p/dsjbg7YMNn/

I have tested your code and sometimes it works, sometimes it doesn’t. If you search on Code Utility you will find plenty of similar problems.

You have 2 options:

  1. Migrate to ExoPlayer2 which is far superior that MediaPlayer.
  2. It doesn’t work to play the sound in OnPreparedListener, but you can play it on button click, after it’s prepared:
public class MainActivity extends AppCompatActivity {

    private Button streamButton;
    private boolean isPrepared = false;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        MediaPlayer mediaPlayer = new MediaPlayer();
        try {
            mediaPlayer.setDataSource("http://penguinradio.dominican.edu/Sound%20FX%20Collection/Motorbike.mp3");
        } catch (IOException e) {
            e.printStackTrace();
        }

        mediaPlayer.setOnPreparedListener(mp -> {
            Toast.makeText(MainActivity.this, "Ready to Play", Toast.LENGTH_SHORT).show();
            isPrepared = true;
            streamButton.setVisibility(View.VISIBLE);
        });

        mediaPlayer.setOnCompletionListener(mp -> {
            mp.release();
            isPrepared = false;
            streamButton.setVisibility(View.INVISIBLE);
        });

        mediaPlayer.prepareAsync();

        streamButton = findViewById(R.id.streamButton);
        streamButton.setOnClickListener(v -> {
            if (isPrepared) {
                mediaPlayer.start();
            }
        });

    }
}