setAudioStreamType deprecated method, how i can replace it?

感情迁移 提交于 2020-07-18 21:43:31

问题


I am trying make a radio streaming app in android studio using mediaplayer, but i when compile shows the next error:

uses or overrides a deprecated API. Recompile with -Xlint:deprecation for details.

I was search in android documentation and i should reemplace this method for setAudioAttributes, i how can change it? i am new using android studio.

Thanks.

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

}


回答1:


mp.setAudioStreamType(AudioManager.STREAM_MUSIC);

to

mp.setAudioAttributes(
            new AudioAttributes
               .Builder()
               .setContentType(AudioAttributes.CONTENT_TYPE_MUSIC)
               .build());



回答2:


Use setAudioAttributes(AudioAttributes) instead of setAudioStreamType()

The Google Documentation says:

Sets the audio stream type for this MediaPlayer. See AudioManager for a list of stream types. Must call this method before prepare() or prepareAsync() in order for the target stream type to become effective thereafter.




回答3:


It will work on all API levels

MediaPlayer mediaPlayer = new MediaPlayer();
Uri audioUri = Uri.parse(strUri);
    try {
        mediaPlayer.setDataSource(context, audioUri);
    } catch (IOException e) {
        e.printStackTrace();
    }
    try {
        mediaPlayer.prepare();
    } catch (IOException e) {
        e.printStackTrace();
    }
    mediaPlayer.start();


来源:https://stackoverflow.com/questions/56744911/setaudiostreamtype-deprecated-method-how-i-can-replace-it

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!