Android之MediaPlayer播放音樂並實現進度條執行個體

來源:互聯網
上載者:User

首先,說明我們是從sd卡裡讀檔案,來播放檔案!!

1、:

提前工作,往sd卡裡放音樂檔案,

2、布局檔案main.xml

<?xml version="1.0" encoding="utf-8"?><LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"    android:layout_width="fill_parent"    android:layout_height="fill_parent"    android:orientation="vertical" ><TextView     android:layout_width="wrap_content"    android:layout_height="wrap_content"    android:text="歌曲名:"/><TextView     android:layout_width="wrap_content"    android:layout_height="wrap_content"    android:text="blueflawer.mp3"/><Button     android:layout_width="wrap_content"    android:layout_height="wrap_content"    android:text="播放"    android:id="@+id/play_pause"/><Button     android:layout_width="wrap_content"    android:layout_height="wrap_content"    android:text="重設"    android:id="@+id/reset"/><SeekBar     android:layout_width="fill_parent"    android:layout_height="wrap_content"    android:id="@+id/seekbar"/></LinearLayout>

3、activity類

package cn.csdn.activity;import java.io.File;import java.io.IOException;import java.util.Timer;import java.util.TimerTask;import android.app.Activity;import android.media.MediaPlayer;import android.os.Bundle;import android.os.Environment;import android.view.View;import android.view.View.OnClickListener;import android.widget.Button;import android.widget.SeekBar;import android.widget.SeekBar.OnSeekBarChangeListener;public class MyPlayerActivity extends Activity {private Button play_pause, reset;private SeekBar seekbar;private boolean ifplay = false;private MediaPlayer player = null;private String musicName = "blueflawer.mp3";private boolean iffirst = false;private Timer mTimer;  private TimerTask mTimerTask; private boolean isChanging=false;//互斥變數,防止定時器與SeekBar拖動時進度衝突 public void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);setContentView(R.layout.main);player = new MediaPlayer();findViews();// 各組件}private void findViews() {play_pause = (Button) findViewById(R.id.play_pause);reset = (Button) findViewById(R.id.reset);play_pause.setOnClickListener(new MyClick());reset.setOnClickListener(new MyClick());seekbar = (SeekBar) findViewById(R.id.seekbar);seekbar.setOnSeekBarChangeListener(new MySeekbar());}class MyClick implements OnClickListener {public void onClick(View v) {File file = new File(Environment.getExternalStorageDirectory(),musicName);// 判斷有沒有要播放的檔案if (file.exists()) {switch (v.getId()) {case R.id.play_pause:if (player != null && !ifplay) {play_pause.setText("暫停");if (!iffirst) {player.reset();try {player.setDataSource(file.getAbsolutePath());player.prepare();// 準備} catch (IllegalArgumentException e) {e.printStackTrace();} catch (IllegalStateException e) {e.printStackTrace();} catch (IOException e) {e.printStackTrace();}seekbar.setMax(player.getDuration());//設定進度條//----------定時器記錄播放進度---------//          mTimer = new Timer();          mTimerTask = new TimerTask() {              @Override              public void run() {                   if(isChanging==true) {                     return;                  }                seekbar.setProgress(player.getCurrentPosition());            }          };         mTimer.schedule(mTimerTask, 0, 10); iffirst=true;}player.start();// 開始ifplay = true;} else if (ifplay) {play_pause.setText("繼續");player.pause();ifplay = false;}break;case R.id.reset:if (ifplay) {player.seekTo(0);} else {player.reset();try {player.setDataSource(file.getAbsolutePath());player.prepare();// 準備player.start();// 開始} catch (IllegalArgumentException e) {e.printStackTrace();} catch (IllegalStateException e) {e.printStackTrace();} catch (IOException e) {e.printStackTrace();}}break;}}}}//進度條處理class MySeekbar implements OnSeekBarChangeListener {public void onProgressChanged(SeekBar seekBar, int progress,boolean fromUser) {}public void onStartTrackingTouch(SeekBar seekBar) {isChanging=true;  }public void onStopTrackingTouch(SeekBar seekBar) {player.seekTo(seekbar.getProgress());isChanging=false;  }}//來電處理protected void onDestroy() {if(player != null){if(player.isPlaying()){player.stop();}player.release();}super.onDestroy();}protected void onPause() {if(player != null){if(player.isPlaying()){player.pause();}}super.onPause();}protected void onResume() {if(player != null){if(!player.isPlaying()){player.start();}}super.onResume();}}

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.