setAudioStreamType 已弃用,如何替换?

Jei*_*elo 10 android android-mediaplayer

我正在尝试使用 MediaPlayer 在 Android Studio 中制作一个广播流应用程序,但是当我编译它时显示下一个错误:

使用或覆盖已弃用的 API。使用 -Xlint:deprecation 重新编译以获取详细信息。

我在 Android 文档中搜索,我应该将这种方法替换为setAudioAttributes,我该如何更改它?

public class Radio extends Fragment {

    Button play_pause;
    MediaPlayer mp;
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.radio, container, false);
        play_pause = (Button) view.findViewById(R.id.btnplay);
        try {
               mp.setAudioStreamType(AudioManager.STREAM_MUSIC);
                mp.setDataSource("http://198.27.83.65:9962/;stream.mp3");
                mp.prepareAsync();
         }
         catch (Exception e){
             Toast.makeText(getContext(),"Error" + e,Toast.LENGTH_SHORT).show();
         }
         //mp = MediaPlayer.create(this.getContext(), R.raw.radio);
            play_pause.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                         if(mp.isPlaying()) {
                            mp.pause();
                            Toast.makeText(getContext(),"Stop",Toast.LENGTH_SHORT).show();
                        }
                        else {
                            mp.start();
                            Toast.makeText(getContext(),"Start",Toast.LENGTH_SHORT).show();
                        }
                }
            });
        return view;
    }
}
Run Code Online (Sandbox Code Playgroud)

fan*_*hzh 39

mp.setAudioStreamType(AudioManager.STREAM_MUSIC);
Run Code Online (Sandbox Code Playgroud)

mp.setAudioAttributes(
            new AudioAttributes
               .Builder()
               .setContentType(AudioAttributes.CONTENT_TYPE_MUSIC)
               .build());
Run Code Online (Sandbox Code Playgroud)

setAudioStreamType 在 API 级别 26 中已弃用,您必须使用新方法 setAudioAttributes

根据文件: You must call this method before prepare() or prepareAsync() in order for the audio attributes to become effective thereafter.