读书人

Android构建音频播放器课程(三)

发布时间: 2012-07-28 12:25:13 作者: rapoo

Android构建音频播放器教程(三)

10. 为Audio Player写相关类文件 打开你的主要活动类(MainActivity)处理主要player界面,并且继承 OnCompletionListener, SeekBar.OnSeekBarChangeListener.在这种情况下,我的主要活动名称是AndroidBuildingMusicPlayerActivity。 AndroidBuildingMusicPlayerActivity.javapublicclassAndroidBuildingMusicPlayerActivityextendsActivity implementsOnCompletionListener, SeekBar.OnSeekBarChangeListener {现在声明所有变量需要为此音频播放器类。(audio player class)

AndroidBuildingMusicPlayerActivity.javapublicclassAndroidBuildingMusicPlayerActivityextendsActivity implementsOnCompletionListener, SeekBar.OnSeekBarChangeListener { privateImageButton btnPlay; privateImageButton btnForward; privateImageButton btnBackward; privateImageButton btnNext; privateImageButton btnPrevious; privateImageButton btnPlaylist; privateImageButton btnRepeat; privateImageButton btnShuffle; privateSeekBar songProgressBar; privateTextView songTitleLabel; privateTextView songCurrentDurationLabel; privateTextView songTotalDurationLabel; // Media Player private MediaPlayer mp; // Handler to update UI timer, progress bar etc,. privateHandler mHandler =newHandler();; privateSongsManager songManager; privateUtilities utils; privateintseekForwardTime =5000;// 5000 milliseconds privateintseekBackwardTime =5000;// 5000 milliseconds privateintcurrentSongIndex =0; privatebooleanisShuffle =false; privatebooleanisRepeat =false; privateArrayList<HashMap<String, String>> songsList =newArrayList<HashMap<String, String>>();

现在引用XML布局的所有按钮,图像类
AndroidBuildingMusicPlayerActivity.java// All player buttons btnPlay = (ImageButton) findViewById(R.id.btnPlay); btnForward = (ImageButton) findViewById(R.id.btnForward); btnBackward = (ImageButton) findViewById(R.id.btnBackward); btnNext = (ImageButton) findViewById(R.id.btnNext); btnPrevious = (ImageButton) findViewById(R.id.btnPrevious); btnPlaylist = (ImageButton) findViewById(R.id.btnPlaylist); btnRepeat = (ImageButton) findViewById(R.id.btnRepeat); btnShuffle = (ImageButton) findViewById(R.id.btnShuffle); songProgressBar = (SeekBar) findViewById(R.id.songProgressBar); songTitleLabel = (TextView) findViewById(R.id.songTitle); songCurrentDurationLabel = (TextView) findViewById(R.id.songCurrentDurationLabel); songTotalDurationLabel = (TextView) findViewById(R.id.songTotalDurationLabel); // Mediaplayer mp =newMediaPlayer(); songManager =newSongsManager(); utils =newUtilities(); // Listeners songProgressBar.setOnSeekBarChangeListener(this);// Important mp.setOnCompletionListener(this);// Important // Getting all songs list songsList = songManager.getPlayList();

1.加载播放列表(PlayList) 为playlist button写单击事件侦听器,在点击播放按钮时我们需要加载PlayListAcitivity.java ,从列表中选择一个特定的歌曲上我们需要得到songIndex。 AndroidBuildingMusicPlayerActivity.java/** * Button Click event for Play list click event * Launches list activity which displays list of songs * */ btnPlaylist.setOnClickListener(newView.OnClickListener() { @Override publicvoidonClick(View arg0) { Intent i =newIntent(getApplicationContext(), PlayListActivity.class); startActivityForResult(i,100); } });
接收选定的歌曲索引增加以下功能(请确保您添加此功能以外的onCreate方法)
AndroidBuildingMusicPlayerActivity.java/** * Receiving song index from playlist view * and play the song * */ @Override protectedvoidonActivityResult(intrequestCode, intresultCode, Intent data) { super.onActivityResult(requestCode, resultCode, data); if(resultCode == 100){ currentSongIndex = data.getExtras().getInt("songIndex"); // play selected song playSong(currentSongIndex); } }

2.Playing Song(播放歌曲) 添加以下功能添加到你的类,这个函数接受songIndex作为参数并播放。当开始播放一首歌切换播放按钮暂停按钮状态。AndroidBuildingMusicPlayerActivity.java/** * Function to play a song * @param songIndex - index of song * */ publicvoid playSong(intsongIndex){ // Play song try{ mp.reset(); mp.setDataSource(songsList.get(songIndex).get("songPath")); mp.prepare(); mp.start(); // Displaying Song title String songTitle = songsList.get(songIndex).get("songTitle"); songTitleLabel.setText(songTitle); // Changing Button Image to pause image btnPlay.setImageResource(R.drawable.btn_pause); // set Progress bar values songProgressBar.setProgress(0); songProgressBar.setMax(100); // Updating progress bar updateProgressBar(); }catch(IllegalArgumentException e) { e.printStackTrace(); }catch(IllegalStateException e) { e.printStackTrace(); }catch(IOException e) { e.printStackTrace(); } }

3.Forward / Backward button click events(向前向后事件监听) 添加按钮事件侦听器,歌指定秒前和向后 1.前进按钮单击事件-移动歌曲以指定数量的秒向前,
AndroidBuildingMusicPlayerActivity.java/** * Forward button click event * Forwards song specified seconds * */ btnForward.setOnClickListener(newView.OnClickListener() { @Override publicvoidonClick(View arg0) { // get current song position intcurrentPosition = mp.getCurrentPosition(); // check if seekForward time is lesser than song duration if(currentPosition + seekForwardTime <= mp.getDuration()){ // forward song mp.seekTo(currentPosition + seekForwardTime); }else{ // forward to end position mp.seekTo(mp.getDuration()); } } });
2.向后按钮单击事件-移动歌曲以指定秒数落后,
AndroidBuildingMusicPlayerActivity.java/** * Backward button click event * Backward song to specified seconds * */ btnBackward.setOnClickListener(newView.OnClickListener() { @Override publicvoidonClick(View arg0) { // get current song position intcurrentPosition = mp.getCurrentPosition(); // check if seekBackward time is greater than 0 sec if(currentPosition - seekBackwardTime >= 0){ // forward song mp.seekTo(currentPosition - seekBackwardTime); }else{ // backward to starting position mp.seekTo(0); } } });

4.Next / Back button click events(上一首下一首事件监听) 点击添加按钮侦听器的下一个和上一个。
1.Next按钮单击事件-从播放列表播放下一首歌曲(不是最后一首)AndroidBuildingMusicPlayerActivity.java/** * Next button click event * Plays next song by taking currentSongIndex + 1 * */ btnNext.setOnClickListener(newView.OnClickListener() { @Override publicvoidonClick(View arg0) { // check if next song is there or not if(currentSongIndex < (songsList.size() - 1)){ playSong(currentSongIndex +1); currentSongIndex = currentSongIndex +1; }else{ // play first song playSong(0); currentSongIndex =0; } } });
2.后退按钮单击事件——播放前一首歌曲(不是第一首) AndroidBuildingMusicPlayerActivity.java/** * Back button click event * Plays previous song by currentSongIndex - 1 * */ btnPrevious.setOnClickListener(newView.OnClickListener() { @Override publicvoidonClick(View arg0) { if(currentSongIndex > 0){ playSong(currentSongIndex - 1); currentSongIndex = currentSongIndex - 1; }else{ // play last song playSong(songsList.size() - 1); currentSongIndex = songsList.size() - 1; } } });
5.更新SeekBar的进度和时间 要更新进度条计时器,我实现了在后台运行一个后台线程,使用一个HandlerAndroidBuildingMusicPlayerActivity.java/** * Update timer on seekbar * */ publicvoidupdateProgressBar() { mHandler.postDelayed(mUpdateTimeTask,100); } /** * Background Runnable thread * */ privateRunnable mUpdateTimeTask = new Runnable() { publicvoidrun() { longtotalDuration = mp.getDuration(); longcurrentDuration = mp.getCurrentPosition(); // Displaying Total Duration time songTotalDurationLabel.setText(""+utils.milliSecondsToTimer(totalDuration)); // Displaying time completed playing songCurrentDurationLabel.setText(""+utils.milliSecondsToTimer(currentDuration)); // Updating progress bar intprogress = (int)(utils.getProgressPercentage(currentDuration, totalDuration)); //Log.d("Progress", ""+progress); songProgressBar.setProgress(progress); // Running this thread after 100 milliseconds mHandler.postDelayed(this,100); } }; /** * * */ @Override publicvoidonProgressChanged(SeekBar seekBar, int progress, boolean fromTouch) { } /** * When user starts moving the progress handler * */ @Override publicvoidonStartTrackingTouch(SeekBar seekBar) { // remove message Handler from updating progress bar mHandler.removeCallbacks(mUpdateTimeTask); } /** * When user stops moving the progress hanlder * */ @Override publicvoidonStopTrackingTouch(SeekBar seekBar) { mHandler.removeCallbacks(mUpdateTimeTask); inttotalDuration = mp.getDuration(); intcurrentPosition = utils.progressToTimer(seekBar.getProgress(), totalDuration); // forward or backward to certain seconds mp.seekTo(currentPosition); // update timer progress again updateProgressBar(); }

6.Repeat button click event(事件监听) 在单击按钮重复isRepeat我们需要设置为true,反之亦然。我们也需要改变图像源重复按钮来集中状态
AndroidBuildingMusicPlayerActivity.java/** * Button Click event for Repeat button * Enables repeat flag to true * */ btnRepeat.setOnClickListener(newView.OnClickListener() { @Override publicvoidonClick(View arg0) { if(isRepeat){ isRepeat = false; Toast.makeText(getApplicationContext(),"Repeat is OFF", Toast.LENGTH_SHORT).show(); btnRepeat.setImageResource(R.drawable.btn_repeat); }else{ // make repeat to true isRepeat = true; Toast.makeText(getApplicationContext(),"Repeat is ON", Toast.LENGTH_SHORT).show(); // make shuffle to false isShuffle = false; btnRepeat.setImageResource(R.drawable.btn_repeat_focused); btnShuffle.setImageResource(R.drawable.btn_shuffle); } } });

7.Shuffle button click event(事件监听)“洗牌”按钮上,我们需要设置isShuffle为true,反之亦然。此外,我们需要改变图像源洗牌按钮集中状态。
AndroidBuildingMusicPlayerActivity.java/** * Button Click event for Shuffle button * Enables shuffle flag to true * */ btnShuffle.setOnClickListener(newView.OnClickListener() { @Override publicvoidonClick(View arg0) { if(isShuffle){ isShuffle = false; Toast.makeText(getApplicationContext(),"Shuffle is OFF", Toast.LENGTH_SHORT).show(); btnShuffle.setImageResource(R.drawable.btn_shuffle); }else{ // make repeat to true isShuffle=true; Toast.makeText(getApplicationContext(),"Shuffle is ON", Toast.LENGTH_SHORT).show(); // make shuffle to false isRepeat = false; btnShuffle.setImageResource(R.drawable.btn_shuffle_focused); btnRepeat.setImageResource(R.drawable.btn_repeat); } } });

8.继承 song onCompletion Listener接口 实现这个监听器很重要,当歌曲播放完毕后他会通知你,在这个方法中,我们需要自动播放下一首歌曲根据重复和shuffle条件。
AndroidBuildingMusicPlayerActivity.java/** * On Song Playing completed * if repeat is ON play same song again * if shuffle is ON play random song * */ @Override publicvoidonCompletion(MediaPlayer arg0) { // check for repeat is ON or OFF if(isRepeat){ // repeat is on play same song again playSong(currentSongIndex); }elseif(isShuffle){ // shuffle is on - play a random song Random rand = new Random(); currentSongIndex = rand.nextInt((songsList.size() - 1) - 0 + 1) + 0; playSong(currentSongIndex); }else{ // no repeat or shuffle ON - play next song if(currentSongIndex < (songsList.size() - 1)){ playSong(currentSongIndex + 1); currentSongIndex = currentSongIndex + 1; }else{ // play first song playSong(0); currentSongIndex = 0; } } }

读书人网 >Android

热点推荐