1. 程式人生 > >android MediaPlayer實現簡單的音樂播放

android MediaPlayer實現簡單的音樂播放

利用MediaPlayer進行播放音樂,音訊格式包括mp3,mp4等。(在android studio下進行實現)

首先在res下建立raw檔案,並放入音訊檔案(這裡放了一個mp3,一個mp4進行測試)


先設定畫面,一個Button按鈕,用來控制開始和暫停;一個SeekBar進度條,用來觀察歌曲播放進度和通過拖拉調整進度。

main.xml

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent"
    android:layout_height="match_parent" android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    android:paddingBottom="@dimen/activity_vertical_margin" tools:context=".main">

    <Button android:id="@+id/ButtonPlayStop"
        android:text="@string/play_str"
        android:textSize="15pt"
        android:textStyle="bold"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content" />

    <SeekBar android:id="@+id/SeekBar01"
        android:layout_height="wrap_content"
        android:layout_width="fill_parent"
        android:layout_below="@id/ButtonPlayStop" />
</RelativeLayout>
設定資料檔案 res/values/strings
<resources>
    <string name="app_name">Multimedia</string>

    <string name="play_str">PLAY</string>
    <string name="pause_str">PAUSE</string>

    <string name="hello_world">Hello world!</string>
    <string name="action_settings">Settings</string>
</resources>

最後就是主介面的函式實現
package com.example.miki.multimedia;

import android.app.Activity;
import android.media.MediaPlayer;
import android.os.Bundle;
import android.os.Handler;
import android.view.Menu;
import android.view.MenuItem;
import android.view.MotionEvent;
import android.view.View;
import android.widget.Button;
import android.widget.SeekBar;

public class main extends Activity {

    private Button buttonplaystop;
    private MediaPlayer mediaplayer;
    private SeekBar seekBar;
    private final Handler handler=new Handler();
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        initViews();
    }

    private  void initViews(){
        buttonplaystop =(Button) findViewById(R.id.ButtonPlayStop);  // 控制 開始 和暫停

        /*****************控制按鈕的點選事件****************************/
        buttonplaystop.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                buttonClick();
            }
        });
        /***設定音訊的位置***/
        mediaplayer=MediaPlayer.create(this,R.raw.raw1);
        seekBar=(SeekBar) findViewById(R.id.SeekBar01);
        seekBar.setMax(mediaplayer.getDuration());
        seekBar.setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent event) {
                seekChange(v);  /*****調整進度條時呼叫的方法*****/
                return false;
            }
        });
    }

    public  void startPlayProgressUpdater(){
        seekBar.setProgress(mediaplayer.getCurrentPosition());

        if(mediaplayer.isPlaying()) {
            Runnable notification = new Runnable() {
                @Override
                public void run() {
                    startPlayProgressUpdater();
                }
            };
            handler.postDelayed(notification,1000);
        }else {
            mediaplayer.pause();
            buttonplaystop.setText(getString(R.string.play_str));
            seekBar.setProgress(0);
        }
    }

    private void seekChange(View v) {
        if(mediaplayer.isPlaying()){
            SeekBar sb=(SeekBar)v;
            mediaplayer.seekTo(sb.getProgress());
        }
    }

    /*****************控制按鈕的點選事件****************************/
    private void buttonClick() {
        /*********開始狀態******/
        if(buttonplaystop.getText()==getString(R.string.play_str)) {
            buttonplaystop.setText(R.string.pause_str);
            try {
                mediaplayer.start();
                startPlayProgressUpdater();
            }catch (IllegalStateException e) {
                mediaplayer.pause();
            }
        }else {  /*********暫停狀態******/
            buttonplaystop.setText(getString(R.string.play_str));
            mediaplayer.pause();
        }
    }
    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.menu_main, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        int id = item.getItemId();

        //noinspection SimplifiableIfStatement
        if (id == R.id.action_settings) {
            return true;
        }

        return super.onOptionsItemSelected(item);
    }
}

執行時的結果: