Android本地网络播放

来源:互联网 发布:小米3微信无法连接网络 编辑:程序博客网 时间:2024/06/05 00:56

和本地音乐不同的是异步准备,以及在异步准备完毕的时候采取回调方式来进行音乐的播放

public class MainActivity extends Activity {private TextView et_path;private Button bt_play;private Button bt_pause;private Button bt_stop;private Button bt_replay;private MediaPlayer mediaPlayer;@Overrideprotected void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);setContentView(R.layout.activity_main);init();}private void init() {et_path = (TextView) findViewById(R.id.et_path);bt_play = (Button) findViewById(R.id.bt_play);bt_pause = (Button) findViewById(R.id.bt_pause);bt_stop = (Button) findViewById(R.id.bt_stop);bt_replay = (Button) findViewById(R.id.bt_replay);}public void play(View view) {String path = et_path.getText().toString();if(!path.startsWith("http://")){Toast.makeText(getApplicationContext(), "文件路径错误", Toast.LENGTH_SHORT).show();return;}try {mediaPlayer = new MediaPlayer();mediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);mediaPlayer.setDataSource(path);mediaPlayer.prepareAsync();//异步准备mediaPlayer.setOnPreparedListener(new OnPreparedListener() {//异步准备完毕的回调方法@Overridepublic void onPrepared(MediaPlayer mp) {mediaPlayer.start();//开始播放bt_play.setEnabled(false);//设置按钮不可按}});mediaPlayer.setOnCompletionListener(new OnCompletionListener() {//播放完成时的回调方法@Overridepublic void onCompletion(MediaPlayer mp) {bt_play.setEnabled(true);//设置按钮可按}});} catch (Exception e) {e.printStackTrace();Toast.makeText(getApplicationContext(), "播放失败", Toast.LENGTH_SHORT).show();}}public void pause(View view) {if(mediaPlayer!=null&&mediaPlayer.isPlaying()){//在播放状态按暂停后mediaPlayer.pause();//播放暂停bt_pause.setText("继续");//暂停按钮显示继续}else if(mediaPlayer!=null&&!mediaPlayer.isPlaying()){//在暂停状态按继续后mediaPlayer.start();//播放继续bt_pause.setText("暂停");//暂停按钮显示暂停}}public void stop(View view) {if(mediaPlayer!=null&&mediaPlayer.isPlaying()){mediaPlayer.stop();//暂停播放mediaPlayer.release();//释放资源mediaPlayer = null;}}public void replay(View view) {if(mediaPlayer!=null){mediaPlayer.seekTo(0);}else{play(view);}}}


效果图和本地音乐播放一样。

0 0
原创粉丝点击