Android本地網路播放

我叫阿狸貓發表於2014-12-08

和本地音樂不同的是非同步準備,以及在非同步準備完畢的時候採取回撥方式來進行音樂的播放

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;

	@Override
	protected 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() {		//非同步準備完畢的回撥方法
				@Override
				public void onPrepared(MediaPlayer mp) {
					mediaPlayer.start();										//開始播放
					bt_play.setEnabled(false);									//設定按鈕不可按
				}
			});
			
			mediaPlayer.setOnCompletionListener(new OnCompletionListener() {	//播放完成時的回撥方法
				@Override
				public 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);
		}
	}
}


效果圖和本地音樂播放一樣。

相關文章