MediaPlayer 损坏 url 问题

MediaPlayer broken url issue

我在我的项目中使用简单的 MediaPlayer 来收听我的音频。

如果音频 link 损坏或不正确,我的应用程序会冻结(一段时间后崩溃)。

MediaPlayer mediaPlayer = new MediaPlayer();
mediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
try {
    mediaPlayer.setDataSource("my audio link");
} catch (IOException e) {
    e.printStackTrace();
}
try {
    mediaPlayer.prepare();
} catch (IOException e) {
    e.printStackTrace();
}
mediaPlayer.start();

感谢您的帮助。

更新:

logcat

2019-12-15 06:00:04.090 7692-7692/com.swipe.app W/MediaPlayer: Use of stream types is deprecated for operations other than volume control
2019-12-15 06:00:04.090 7692-7692/com.swipe.app W/MediaPlayer: See the documentation of setAudioStreamType() for what to use instead with android.media.AudioAttributes to qualify your playback use case
2019-12-15 06:00:34.824 7692-7806/com.swipe.app E/MediaPlayerNative: error (1, -2147483648)
2019-12-15 06:00:34.825 7692-7692/com.swipe.app W/System.err:     at android.media.MediaPlayer._prepare(Native Method)
2019-12-15 06:00:34.825 7692-7692/com.swipe.app W/System.err:     at android.media.MediaPlayer.prepare(MediaPlayer.java:1274)
2019-12-15 06:00:34.827 7692-7692/com.swipe.app E/MediaPlayerNative: start called in state 0, mPlayer(0xc68284a0)
2019-12-15 06:00:34.827 7692-7692/com.swipe.app E/MediaPlayerNative: error (-38, 0)
2019-12-15 06:00:34.836 7692-7692/com.swipe.app E/MediaPlayer: Error (-38,0)

尝试替换

mediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC)

使用以下代码

final AudioAttributes audioAttributes =new AudioAttributes
            .Builder()
            .setContentType(AudioAttributes.CONTENT_TYPE_MUSIC)
            .build();
mediaPlayer.setAudioAttributes(audioAttributes);

您可以将 AudioAttributes 类型更改为您想要的类型。请参阅文档。 https://developer.android.com/reference/android/media/AudioAttributes

原因是 setAudioStreamType 是贬值方法。参见 https://developer.android.com/reference/android/media/MediaPlayer