Android Studio Android工作室:MediaPlayer setDataSource URL无法播放音乐

ulydmbyx  于 2022-11-16  发布在  Android
关注(0)|答案(2)|浏览(130)

打开应用程序没有任何错误。但不能播放音乐。但可以播放本地机器上的音乐。互联网连接正常。
我已在AndroidManiFest.xml中启用互联网权限
<uses-permission android:name="android.permission.INTERNET" />
我已启用http权限。
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();

完整代码:https://paste.ubuntu.com/p/dsjbg7YMNn/

du7egjpx

du7egjpx1#

我已经测试过你的代码,有时它能用,有时不能用。如果你在Stack Overflow上搜索,你会发现很多类似的问题。
您有两个选项:
1.迁移到ExoPlayer2,它远远上级MediaPlayer
1.在OnPreparedListener中无法播放声音,但您可以在准备好声音后单击按钮播放声音:

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();
            }
        });

    }
}
afdcj2ne

afdcj2ne2#

试试这个:

if(mediaPlayer != null ){

                    if (mediaPlayer.isPlaying()){mediaPlayer.stop();}

                    mediaPlayer.reset(); //this line is important!

                    String path = File.separator + "sdcard" + File.separator + utilsFields.repoDirRoot + File.separator + media.mp4;

                    try {
                        mediaPlayer.setDataSource(path);
                    }catch (Exception ignored){}

                    try {
                        mediaPlayer.prepare();
                    }catch (Exception ignored){}

                    mediaPlayer.start();

                }

相关问题