创建动态媒体播放器Android

时间:2014-03-15 23:52:20

标签: java android stream streaming media-player

我尝试制作流媒体广播应用程序。我为媒体播放器使用了服务。当radio1正在播放时,我点击radio2,radio1是停止播放radio2吗? (抱歉我的英文不好:D) 这是我的代码

MyRadio.java

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;

public class MyRadio extends Activity implements OnClickListener {
Button radio1, radio2,  stop;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_service);
    radio1 = (Button) findViewById(R.id.button1);
    radio2 = (Button) findViewById(R.id.button3);
    stop = (Button) findViewById(R.id.button2);

    radio1.setOnClickListener(this);
    radio2.setOnClickListener(this);
    stop.setOnClickListener(this);
}

public void onClick(View v) {
    switch (v.getId()) {
    case R.id.button1:
        Intent i = new Intent(getApplicationContext(), MyService.class);
        i.putExtra(MyService.URL, "http://5.231.68.21:8004");
        startService(i);
        break;

    case R.id.button3:
        Intent j = new Intent(getApplicationContext(), MyService.class);
        j.putExtra(MyService.URL, "http://50.117.121.163:80");
        startService(j);
        break;

    case R.id.button2:
        stopService(new Intent(this, MyService.class));
        break;
    }

}
  }

MyService.java

import java.io.IOException;
import android.app.Service;
import android.content.Intent;
import android.media.MediaPlayer;
import android.os.IBinder;

public class MyService extends Service implements
    MediaPlayer.OnPreparedListener, MediaPlayer.OnErrorListener {

public static String URL;
private MediaPlayer mp;

public IBinder onBind(Intent arg0) {
    return null;
}

@Override
public void onCreate() {
    super.onCreate();
}

@Override
public int onStartCommand(Intent intent, int flags, int startId) {
    String i = intent.getStringExtra(URL);
    String url = "" + i;
    mp = new MediaPlayer();
    mp.setOnPreparedListener(this);
    try {
        mp.setDataSource(url);
    } catch (IllegalArgumentException e) {
        e.printStackTrace();
    } catch (SecurityException e) {
        e.printStackTrace();
    } catch (IllegalStateException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }
    mp.prepareAsync();

    return START_NOT_STICKY;
}

public void onDestroy() {
    mp.stop();
}

@Override
public void onPrepared(MediaPlayer mp) {
    // TODO Auto-generated method stub
    mp.start();
}

public boolean onError(MediaPlayer mp, int what, int extra) {

    mp.stop();
    mp.release();
    mp = null;
    return true;
}
 }

1 个答案:

答案 0 :(得分:0)

每当你按下一个按钮,你就会创建一个新的MediaPlayer实例并告诉它播放一首歌。你永远不会破坏/阻止你之前创建的那个。