android开发:一个简单的MP3播放器的实例(MediaPlayer)

QQ截图20160617161520

 

 

使用的是MediaPlayer这个对象,实现的方法:

  • 扫描Music的目录,把文件add到array中。
  • 然后实用化MediaPlayer对象。
  • 接着实现start、stop、pause、next等播放方法。

播放的方法:

uri = Uri.parse("/mnt/sdcard/Music/1.MP3");
try {
    mp.setDataSource(mContext, uri);
    mp.prepare();
} catch (IOException e) {
    e.printStackTrace();
}
mp.start();

暂停的方法:

mp.pause();

停止的方法:

mp.stop();

下一首的方法:

mp.reset();
uri = Uri.parse("/mnt/sdcard/Music/2.MP3");
try {
 mp.setDataSource(mContext, uri);
 mp.prepare();
} catch (IOException e) {
 e.printStackTrace();
}
mp.start();

以下是整个文件的代码:

package com.test.testmedia;

import android.annotation.TargetApi;
import android.content.Context;
import android.media.MediaPlayer;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.util.Log;
import android.view.View;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.Button;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Timer;
import java.util.TimerTask;

public class MainActivity extends AppCompatActivity {

    private static final String TAG = "MediaLog";
    Button start,stop,pause,start2,stop2,pause2;
    MediaPlayer mp;
    Uri uri;
    Context mContext;
    Timer timer;
    TimerTask tt;
    HandlerEx handler;
    Bundle bundle;

    int audiolenth = -1;
    int MediaPlayerstate = -1;
    private ArrayList<String> music = new ArrayList<String>();
    int pos = -1;


    public class HandlerEx extends Handler{
        public void handleMessage(Message msg) {
            if(msg.what == 1){
                if(bundle.containsKey("title")){
                    Log.i(TAG,bundle.getString("title"));
                    setTitle(bundle.getString("title"));
                }

            }

        }
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);

        findid();
        init();
    }


    private void findid() {
        start = (Button)findViewById(R.id.Start);
        stop = (Button)findViewById(R.id.Stop);
        pause = (Button)findViewById(R.id.Pause);

        start2 = (Button)findViewById(R.id.start2);
        stop2 = (Button)findViewById(R.id.stop2);
        pause2 = (Button)findViewById(R.id.pause2);

        mContext = this;
        mp = new MediaPlayer();
        bundle = new Bundle();
        timer = new Timer();
        tt = new TimerTask() {
            @Override
            public void run() {
                Message msg = handler.obtainMessage();
                msg.what=1;

                switch (MediaPlayerstate){
                    case 1:
                        bundle.putString("title","正在播放:" + (int) (mp.getCurrentPosition() / 1000) + "/" + audiolenth);
                        break;
                    case 2:
                        bundle.putString("title","已停止");
                        break;
                    case 3:
                        bundle.putString("title","已暂停");
                        break;
                    default:
                        bundle.putString("title",getString(R.string.app_name));
                        break;
                }

                handler.sendMessage(msg);
            }
        };
        timer.schedule(tt,0,1000);

        handler = new HandlerEx();

        getFils("/mnt/sdcard/Music/", ".mp3", true);
    }

    /**
     * 搜索文件
     * @param path 如:/mnt/sdcard/Music/
     * @param suffix 单个请使用.mp3,多个如:.mp3;.log
     * @param isSon 是否包含子目录
     */
    private void getFils(String path,String suffix,boolean isSon){
        File[] files = new File(path).listFiles();
        for (int i = 0; i < files.length; i++){
            File f = files[i];
            if(f.isFile()){
                String _name = f.getPath();
                String _suf = _name.substring(_name.lastIndexOf(".")).toLowerCase();
                suffix = suffix.toLowerCase();

                if(suffix.indexOf(_suf) != -1 ){
                    Log.i(TAG,_name);
                    music.add(_name);
                }

                if(!isSon)
                    break;
            }else if (f.isDirectory() && f.getPath().indexOf("/.") == -1){
                getFils(f.getPath(),suffix,isSon);
            }
        }

    }

    private String getMp3(){
        pos++;
        if(pos >= music.size())
            pos = -1;

        return music.get(pos);
    }


    private void init() {
        start.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (start.getText().equals(getString(R.string.start))) {
                    start.setText(getString(R.string.next));
                } else {
                    mp.reset();
                }
                String u = getMp3();
                Log.i(TAG, u);
                uri = Uri.parse(u);
                try {
                    mp.setDataSource(mContext, uri);
                    mp.prepare();
                } catch (IOException e) {
                    e.printStackTrace();
                }
                mp.start();
                audiolenth = (int) mp.getDuration() / 1000;
                MediaPlayerstate = 1;
            }
        });

        stop.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                mp.stop();
                mp.reset();
                MediaPlayerstate = 2;

            }
        });

        pause.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (pause.getText().equals(getString(R.string.pause))) {
                    MediaPlayerstate = 3;
                    mp.pause();
                    pause.setText(getString(R.string.play));
                } else {
                    MediaPlayerstate = 1;
                    mp.start();
                    pause.setText(getString(R.string.pause));
                }
            }
        });

        mp.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
            @Override
            public void onCompletion(MediaPlayer mp) {
                Log.i(TAG, "setOnCompletionListener");
                mp.reset();
                MediaPlayerstate = -1;
                start.callOnClick();
            }
        });



        mp.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
            @Override
            public void onPrepared(MediaPlayer mp) {

                Log.i(TAG, "setOnPreparedListener:" + mp.getDuration());

            }
        });
        

    }

    @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);
    }
}

 

 

 

Leave a Comment

 
Copyright © 2008-2021 lanxinbase.com Rights Reserved. | 粤ICP备14086738号-3 |