使用服务类中的方法停止媒体播放器

时间:2016-10-26 06:09:08

标签: android service android-mediaplayer audio-streaming

我正在构建一个应用程序来从互联网流式传输广播。研究我发现,为此我需要创建一个服务,因为我希望当应用程序最小化时收音机仍在播放。

我创建了服务类并将其调用为我的主要活动,并且我能够传输音频,但现在我想实现一个按钮,以便在用户打开应用程序时停止流式传输,所以我绑定我对我的活动的服务,并创建一个公共方法来停止媒体播放器。这是我的服务类:

public class StreamClass extends Service implements    MediaPlayer.OnPreparedListener{

MediaPlayer mMediaPlayer = new MediaPlayer();
String URL ="http://rfcmedia.streamguys1.com/classicrock.mp3";
private IBinder mBinder = new MyBinder();
private boolean prepared=false;

@Override
public void onCreate() {
    super.onCreate();
    mMediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
}

@Override
public int onStartCommand(Intent intent, int flags, int startId) {

    try {
        mMediaPlayer.setDataSource(URL);
        mMediaPlayer.setOnPreparedListener(this);
        mMediaPlayer.prepareAsync();
    }catch (IOException e){
        e.printStackTrace();
    }
    return super.onStartCommand(intent, flags, startId);
}

@Nullable
@Override
public IBinder onBind(Intent intent) {
    return null;
}

@Override
public void onPrepared(MediaPlayer mp) {
    mp.start();
    prepared=true;
}

public void StopRadio(){
    mMediaPlayer.stop();
}

public class MyBinder extends Binder{
    StreamClass getService(){
        return StreamClass.this;
    }
}

}

这是我的MainActivy:     公共类MainActivity扩展了AppCompatActivity {

private SeekBar volumeSeekbar = null;
private AudioManager audioManager = null;
String URL = "http://rfcmedia.streamguys1.com/classicrock.mp3";
MediaPlayer mediaPlayer = new MediaPlayer();
StreamClass streamClass = new StreamClass();


@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    final Intent i = new Intent(this, StreamClass.class);
    startService(i);
    bindService(i, mServiceConnection, Context.BIND_AUTO_CREATE);

    ImageButton btnStop = (ImageButton) findViewById(R.id.btnStop);

    btnStop.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            streamClass.StopRadio();
        }

    });
}

private ServiceConnection mServiceConnection = new ServiceConnection() {
    @Override
    public void onServiceConnected(ComponentName name, IBinder service) {
        MyBinder myBinder =(MyBinder)service;
        streamClass=myBinder.getService();
    }

    @Override
    public void onServiceDisconnected(ComponentName name) {

    }
};

}

当我点击停止按钮时,我有以下错误: E / MediaPlayer:在状态1中停止调用 E / MediaPlayer:错误(-38,0)

似乎mediaPlayer未处于正确的停止状态。

提前致谢。

0 个答案:

没有答案