我正在尝试使用setAudioAttributes在android studio中制作一个广播流应用程序,但是当我在手机中安装该应用程序时出现下一个错误:
错误java.lang.nullpointerexception:尝试在空对象引用上调用虚方法void android.media.mediaplayer.setaudioattributes(android.media.AudioAttributes)
谢谢。
公共类电台扩展了片段{
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 {
if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.O) {
mp.setAudioAttributes(new AudioAttributes.Builder()
.setContentType(AudioAttributes.CONTENT_TYPE_MUSIC).build());
mp.setDataSource("http://198.27.83.65:9962/;stream.mp3");
mp.prepare();
mp.start();
}
else {
Toast.makeText(getContext(),"Error",Toast.LENGTH_SHORT).show();
}
}
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;
}
}
答案 0 :(得分:0)
在使用mp
变量之前将其初始化。 mp=new MediaPlayer();