音乐播放器

来源:互联网 发布:买吉他知乎 编辑:程序博客网 时间:2024/06/05 21:55
前提是你模拟器里有音乐或者手机上有音乐
//效果




//布局文件

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout


    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:orientation="vertical"
    tools:context="bawei.musicdemo.MainActivity">


<ImageView
    android:src="@drawable/t1"
    android:layout_width="200sp"
    android:layout_height="200sp"/>
    <SeekBar
        android:id="@+id/seekBar"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"/>
    <LinearLayout
        android:orientation="horizontal"
        android:layout_width="match_parent"
        android:layout_height="wrap_content">
    <Button
        android:text="上一首"
        android:id="@+id/lastMusic"
        android:layout_width="wrap_content"
        android:layout_height="match_parent"/>
        <Button
            android:text="下一首"
            android:id="@+id/nextMusic"
            android:layout_width="wrap_content"
            android:layout_height="match_parent"/>
    </LinearLayout>
    <LinearLayout
        android:orientation="horizontal"
        android:layout_width="match_parent"
        android:layout_height="wrap_content">
        <Button
            android:id="@+id/pause"
            android:text="暂停"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"/>
        <Button
            android:id="@+id/begin"
            android:text="开始"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"/>
        <Button
            android:id="@+id/stop"
            android:text="停止"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"/>


    </LinearLayout>
</LinearLayout>


// MainActivity

import android.database.Cursor;
import android.media.MediaPlayer;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.provider.MediaStore;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.SeekBar;
import android.widget.Toast;


import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;


public class MainActivity extends AppCompatActivity {




    private int index=0;
    private Button lastMusic;
    private Button nextMusic;
    private Button begin;
    private Button pause;
    private Button stop;
    private SeekBar seekBar;
    private static final int SEARCH_MUSIC_SUCCESS=0;
   MediaPlayer mp=new MediaPlayer();
    private List<String> list= new ArrayList<>();
   Handler handler=new Handler(){
       @Override
       public void handleMessage(Message msg) {
           Log.d("msg",""+list.size());
           //initstart();


           //得到当前的进度
           int position=mp.getCurrentPosition();
           //得到时间
           int time=mp.getDuration();
           //得到总长度
           int max=seekBar.getMax();
           seekBar.setProgress(position);
           super.handleMessage(msg);
       }
   };
    private  void initPlayer(){


        //后台线程发送消息进行更新进度条一秒更新一次
        final  int milliseconds=100;
        new Thread(){
            @Override
            public void run() {
                while(true){
                    try {
                        sleep(milliseconds);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                    //启动并发送
                    handler.sendEmptyMessage(0);
                }
            }
        }.start();
    }
    //初始化seekbar
    private void initseekBar(){
        seekBar.setMax(mp.getDuration());
        seekBar.setProgress(0);
    }
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        //找控件
        initdata();
        //找音乐
        initfind();
        //让它播
        //initstart();
        //上一首
       // last();
        //下一首
       // next();
        //开始播放
       // initstart();
        //暂停
       // zanting();
        //停止
       // end();




        //启动模式
        /*    IntentFilter filter=new IntentFilter();
        filter.addAction("finish");
        registerReceiver(mFinishReceiver,filter);
        .....
*/


    }
    //给个监听
    View.OnClickListener onClickListener=new View.OnClickListener() {
        @Override
        public void onClick(View view) {
        switch (view.getId()){
            case R.id.lastMusic:
                last();
                break;
            case  R.id.nextMusic:
                next();
                break;
            case R.id.begin:
                initstart();
                break;
            case R.id.pause:
               mp.pause();
                break;
            case R.id.stop:
               mp.stop();
                break;
        }
        }
    };
    //上一首
    private void last() {
   if ((index-1)>=0){
       index--;
       initstart();
   }else {
       Toast.makeText(MainActivity.this,"这已经是第一首了",Toast.LENGTH_SHORT).show();
   }
    }
    //下一首
    private void next() {
        if((index+1)<list.size()){
            index++;
           initstart();
        }else{
            Toast.makeText(this,"您就这点歌啦",Toast.LENGTH_LONG).show();
        }
    }


    private void initstart (){
        if (list.size()>0&&index<list.size()){
            //路径
            String SongPath=list.get(index);
            //释放资源
            mp.reset();
            //加载歌曲文件
            try {
                mp.setDataSource(SongPath);
                //准备
                //mp.release();
                mp.prepare();
                mp.start();
                initseekBar();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        else{
            Toast.makeText(this,"播放列表为空", Toast.LENGTH_SHORT).show();
        }
    }
    private void zanting() {
    }
    private void end() {
    }


    //扫描音乐文件
    private void initfind() {
        Cursor mAudiocursor=this.getContentResolver().query(MediaStore.Audio.Media.EXTERNAL_CONTENT_URI,null,null,null,MediaStore.Audio.AudioColumns.TITLE);//排序方式
        //循环输出歌曲的信息
        List<Map<String,Object>> mlistData=new ArrayList<Map<String,Object>>();
        for(int i=0;i<mAudiocursor.getCount();i++){
            mAudiocursor.moveToNext();
            //找到歌曲标题和总时间对应的列索引
            int indexTitle=mAudiocursor.getColumnIndex(MediaStore.Audio.AudioColumns.TITLE);//歌名
            //艺术家
            int indexARTIST=mAudiocursor.getColumnIndex(MediaStore.Audio.AudioColumns.ARTIST);
            //专辑
            int indexALBUM=mAudiocursor.getColumnIndex(MediaStore.Audio.AudioColumns.ALBUM);
            String strTitle=mAudiocursor.getString(indexTitle);
            String strARTIST=mAudiocursor.getString(indexARTIST);
            String strALBUM=mAudiocursor.getString(indexALBUM);
            Log.d("msg","歌曲名"+strTitle);
            HashMap<String,Object> nowMap=new HashMap<String, Object>();
            nowMap.put("songName",strTitle+"---"+strARTIST+"---"+strALBUM);
            mlistData.add(nowMap);


        }
        list.clear();
        //是否有外部存储设备
        if(Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)){
            new Thread(new Runnable() {
                String[] ext={".mp3"};
                File file=Environment.getExternalStorageDirectory();
                @Override
                public void run() {
                    search(file,ext);
                    handler.sendEmptyMessage(SEARCH_MUSIC_SUCCESS);
                }
            }).start();
        }else{
            Toast.makeText(this,"请插入外部存储设备。。",Toast.LENGTH_LONG).show();
        }
    }
//搜索音乐文件
    private  void search(File file,String[] ext){
        if (file!=null){
            if (file.isDirectory()){
                File[] listFile=file.listFiles();
                if (listFile!=null){
                    for (int i=0;i<listFile.length;i++){
                        search(listFile[i],ext);
                    }
                }
            }else{
                String filename=file.getAbsolutePath();
                for (int i=0;i<ext.length;i++){
                    if (filename.endsWith(ext[i])){
                        list.add(filename);
                        break;
                    }
                }
            }
        }
    }
    private void initdata() {


        seekBar=(SeekBar)findViewById(R.id.seekBar);
        lastMusic=(Button)findViewById(R.id.lastMusic);
        nextMusic=(Button)findViewById(R.id.nextMusic);
        begin=(Button)findViewById(R.id.begin);
        pause=(Button)findViewById(R.id.pause);
        stop=(Button)findViewById(R.id.stop);
        lastMusic.setOnClickListener(onClickListener);
        nextMusic.setOnClickListener(onClickListener);
        begin.setOnClickListener(onClickListener);
        pause.setOnClickListener(onClickListener);
        stop.setOnClickListener(onClickListener);






    }
  /*  protected BroadcastReceiver mFinishReceiver=new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            if("finish".equals(intent.getAction())){
                Log.e("####","I am"+getLocalClassName()+",now finishing myself...");
                finish();
            }
        }
    };*/


}

0 0