龙盟编程博客 | 无障碍搜索 | 云盘搜索神器
快速搜索
主页 > 移动开发 > Android开发 >

Android提高之MediaPlayer播放网络音频的实现方法(2)

时间:2014-08-10 02:30来源:网络整理 作者:网络 点击:
分享到:
test_musicplayer.java是主程序,负责调用Player类,其中关键部分是SeekBarChangeEvent这个SeekBar拖动的事件: SeekBar的Progress是0~SeekBar.getMax()之内的数,而MediaPlayer.

test_musicplayer.java是主程序,负责调用Player类,其中关键部分是SeekBarChangeEvent这个SeekBar拖动的事件:SeekBar的Progress是0~SeekBar.getMax()之内的数,而MediaPlayer.seekTo()的参数是0~MediaPlayer.getDuration()之内数,所以MediaPlayer.seekTo()的参数是(progress/seekBar.getMax())*player.mediaPlayer.getDuration()。

test_musicplayer.java源码如下:

package com.musicplayer;
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.SeekBar;
public class test_musicplayer extends Activity {
 private Button btnPause, btnPlayUrl, btnStop;
 private SeekBar skbProgress;
 private Player player;
 /** Called when the activity is first created. */
 @Override
 public void onCreate(Bundle savedInstanceState) {
 super.onCreate(savedInstanceState);
 setContentView(R.layout.main);
 this.setTitle("在线音乐播放---hellogv编写");
 btnPlayUrl = (Button) this.findViewById(R.id.btnPlayUrl);
 btnPlayUrl.setOnClickListener(new ClickEvent());
 btnPause = (Button) this.findViewById(R.id.btnPause);
 btnPause.setOnClickListener(new ClickEvent());
 btnStop = (Button) this.findViewById(R.id.btnStop);
 btnStop.setOnClickListener(new ClickEvent());
 skbProgress = (SeekBar) this.findViewById(R.id.skbProgress);
 skbProgress.setOnSeekBarChangeListener(new SeekBarChangeEvent());
 player = new Player(skbProgress);
 }
 class ClickEvent implements OnClickListener {
 @Override
 public void onClick(View arg0) {
  if (arg0 == btnPause) {
  player.pause();
  } else if (arg0 == btnPlayUrl) {
  //在百度MP3里随便搜索到的,大家可以试试别的链接
  String url="http://219.138.125.22/myweb/mp3/CMP3/JH19.MP3";
  player.playUrl(url);
  } else if (arg0 == btnStop) {
  player.stop();
  }
 }
 }
 class SeekBarChangeEvent implements SeekBar.OnSeekBarChangeListener {
 int progress;
 @Override
 public void onProgressChanged(SeekBar seekBar, int progress,
  boolean fromUser) {
  // 原本是(progress/seekBar.getMax())*player.mediaPlayer.getDuration()
  this.progress = progress * player.mediaPlayer.getDuration()
   / seekBar.getMax();
 }
 @Override
 public void onStartTrackingTouch(SeekBar seekBar) {

 }
 @Override
 public void onStopTrackingTouch(SeekBar seekBar) {
  // seekTo()的参数是相对与影片时间的数字,而不是与seekBar.getMax()相对的数字
  player.mediaPlayer.seekTo(progress);
 }
 }
}

感兴趣的读者可以亲自动手调试一下本文实例代码,相信会对大家理解Android程序设计起到一定的促进作用。

精彩图集

赞助商链接