Android0910<十五>(简单的音乐播放器)

MediaPlayer

AndroidManifest.xml

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.example.administrator.musicplayer" >
    <uses-permission android:name="android.permission.READ_CONTACTS"></uses-permission>
    <application
        android:allowBackup="true"
        android:icon="@mipmap/mediaplayer"
        android:label="@string/app_name"
        android:theme="@style/AppTheme" >
        <activity
            android:name=".MainActivity"
            android:label="@string/app_name" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
        <service android:name=".Service.MusicService"></service>
    </application>

</manifest>

activity_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=".MainActivity"
    android:background="@mipmap/background">

    <ListView
        android:id="@+id/listview_music"
        android:layout_width="match_parent"
        android:layout_height="match_parent"></ListView>
    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="vertical"
        android:layout_alignParentBottom="true"
        android:background="#00ffffff">
        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="50dp"
            android:orientation="horizontal"
            android:weightSum="7">
    <Button
        android:id="@+id/btn_play"
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:layout_weight="1"
        android:background="@drawable/btn_play"/>
        </LinearLayout>
        <RelativeLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content">
            <LinearLayout
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:orientation="horizontal"
                android:layout_alignParentRight="true">
            <TextView
                android:id="@+id/text_timenow"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:text="00:00"/>
            <TextView
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:text="/"/>
            <TextView
                android:id="@+id/text_time"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:text="00:00 "/>
            </LinearLayout>
        </RelativeLayout>

        <SeekBar
            android:id="@+id/seekbar_music"
            android:layout_width="match_parent"
            android:layout_height="wrap_content" />
    </LinearLayout>
</RelativeLayout>

activity_music.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="horizontal" android:layout_width="match_parent"
    android:layout_height="match_parent">
    <ImageView
        android:id="@+id/music_img"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        />
    <TextView
        android:id="@+id/text_author"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
      />
    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="---"/>
    <TextView
        android:id="@+id/text_music"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"

        />
</LinearLayout>

MyMusicAdaper.java

public class MyMusicAdapter extends BaseAdapter{
    private LayoutInflater mInflater;
    private File[] musics;

    public MyMusicAdapter(LayoutInflater mInflater, File[] musics) {
        this.mInflater = mInflater;
        this.musics = musics;
    }

    @Override
    public int getCount() {
        return musics.length;
    }

    @Override
    public Object getItem(int position) {
        return position;
    }

    @Override
    public long getItemId(int position) {
        return position;
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        ViewHolder vh=null;
        if (vh==null){
            vh=new ViewHolder();
            convertView=mInflater.inflate(R.layout.activity_music,null);
            vh.textMusic= (TextView) convertView.findViewById(R.id.text_music);
            vh.img= (ImageView) convertView.findViewById(R.id.music_img);
            vh.tvAuthor= (TextView) convertView.findViewById(R.id.text_author);
            convertView.setTag(vh);
        }
        vh= (ViewHolder) convertView.getTag();
        vh.textMusic.setText(musics[position].getName());
        //MediaMetadataRetriever类提供了一个统一的接口用于从一个输入媒体文件中取得帧和元数据
        MediaMetadataRetriever mediaMetadataRetriever=new MediaMetadataRetriever();
        //setDataSource()方法获取数据源
        mediaMetadataRetriever.setDataSource(musics[position].getAbsolutePath());
        //用实例对象调用extractMetadata()方法获得想要的数据信息类型,
        // 传参数为特定的键码,如:METADATA_KEY_ARTIST是获得数据中艺术家的信息。
        String author=mediaMetadataRetriever.extractMetadata(MediaMetadataRetriever.METADATA_KEY_ARTIST);
        if (author!=null){
            vh.tvAuthor.setText(author);
        }else{
            vh.tvAuthor.setText("<未知>");
        }
        //getEmbeddedPicture()方法发现可选的图形或相册/封面与相关的数据源的艺术。如果有多张图片,返回其中的任何一个。
        byte[] image=mediaMetadataRetriever.getEmbeddedPicture();
        if (image!=null){
            //Bitmap是Android系统中的图像处理的最重要类之一。用它可以获取图像文件信息
            //BitmapFactory是从各种源创建位图对象,包括文件、数据流和字节数组。
            //通过decodeByteArray()方法从指定的字节数组中解码一个不可变的位图,返回一个Bitmap类型的值
            //data 第一个参数image是压缩图像数据的字节数组,
            // offset第二个参数是偏移数据,解码器应该开始解析的地方
            // length第三个参数是字节数,开始在偏移辆=量分析
            //opts第四个参数是控制采样和图像是否应该完全解码的选项,或者仅仅是大小返回
            Bitmap bitmap= BitmapFactory.decodeByteArray(image,0,image.length);
            vh.img.setImageBitmap(bitmap);
        }else{
            vh.img.setImageResource(R.mipmap.mediaplayer);
        }

        return convertView;
    }
    class ViewHolder{
        TextView textMusic;
        ImageView img;
        TextView tvAuthor;
    }
}

MyMusicService.java

public class MusicService extends Service{
    private MediaPlayer player;
    @Nullable
    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        int type=intent.getIntExtra("type", Config.START_NEW_MUSIC);
        Log.d("TYPE",""+type);
        switch(type){
            case Config.START_NEW_MUSIC:
                startNewMusic(intent);
                break;
            case Config.MUSIC_SEEK_TO:
                if (player!=null){
                    int progress=intent.getIntExtra("progress",0);
                    player.pause();//暂停播放。
                    player.seekTo(progress);//寻找指定的时间位置。
                    Log.d("当前进度",""+progress);
                    player.start();//开始播放
                }
                break;
        }

        return super.onStartCommand(intent, flags, startId);
    }

    private void startNewMusic(Intent intent) {
        String musicPath=intent.getStringExtra("musicName");
        if (player==null){
            player=new MediaPlayer();
        }else{
            player.seekTo(intent.getIntExtra("progess",0));
        }
        player.reset();//重置MediaPlayer的初始化状态。
        try {
            player.setDataSource(musicPath);
            player.prepare();//准备播放,同步播放
            //注册一个回调函数,当媒体源准备播放时调用。
            player.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
                @Override
                public void onPrepared(MediaPlayer mp) {
                    mp.start();
                    int duration=player.getDuration();
                    Log.d("总时间",""+duration);
                    Intent intent=new Intent("com.play.music");
                    intent.putExtra("type",Config.START_NEW_MUSIC);
                    intent.putExtra("duration",duration);
                    sendBroadcast(intent);
                    MusicPlayThread t=new MusicPlayThread();
                    t.start();
                }
            });
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    class MusicPlayThread extends Thread{
        @Override
        public void run() {
            while(player.isPlaying()){
                int time=player.getCurrentPosition();
                Intent intent=new Intent("com.play.music");
                intent.putExtra("type",1);
                intent.putExtra("currtTime",time);
                sendBroadcast(intent);
                try {
                    Thread.sleep(1000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }
    }
}

Config.java

public class Config {
    public static final int START_NEW_MUSIC=0;
    public static final int MUSIC_SEEK_TO=1;
}

MainActivity.java

public class MainActivity extends AppCompatActivity {
    private ListView mlistMusic;
    private Random mRandom;
    private Button btn_play;
    private File[] musics;
    private SeekBar mSeekBar;
    private int progress;
    MyReceive myReceive;
    private TextView mTime;
    private TextView mNowTime;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        mlistMusic= (ListView) findViewById(R.id.listview_music);
        mSeekBar= (SeekBar) findViewById(R.id.seekbar_music);
        mNowTime= (TextView) findViewById(R.id.text_timenow);
        myReceive=new MyReceive();
        IntentFilter filter=new IntentFilter();
        filter.addAction("com.play.music");
        registerReceiver(myReceive,filter);
        mTime= (TextView) findViewById(R.id.text_time);
        mRandom=new Random();
        btn_play= (Button) findViewById(R.id.btn_play);
        File sdcard= Environment.getExternalStorageDirectory();
        File musicDir=new File(sdcard,"Music");
        musics=musicDir.listFiles();
        MyMusicAdapter mAdapter=new MyMusicAdapter(getLayoutInflater(),musics);
        mlistMusic.setAdapter(mAdapter);
        mlistMusic.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                Intent intent=new Intent(MainActivity.this, MusicService.class);
                intent.putExtra("musicName",musics[position].getAbsolutePath());
                startService(intent);
            }
        });
        btn_play.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

            }
        });
        mSeekBar.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
            @Override
            public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {

            }

            @Override
            public void onStartTrackingTouch(SeekBar seekBar) {

            }

            @Override
            public void onStopTrackingTouch(SeekBar seekBar) {
                Intent intent=new Intent(getApplicationContext(),MusicService.class);
                intent.putExtra("type",Config.MUSIC_SEEK_TO);
                intent.putExtra("progress",seekBar.getProgress());
                Log.d("progress",""+seekBar.getProgress());
                startService(intent);
            }
        });
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        unregisterReceiver(myReceive);
    }

    class MyReceive extends BroadcastReceiver{

        @Override
        public void onReceive(Context context, Intent intent) {
            int type=intent.getIntExtra("type",0);
            SimpleDateFormat format=new SimpleDateFormat("mm:ss");

            switch(type){
                case Config.START_NEW_MUSIC:
                    int duration=intent.getIntExtra("duration",0);
                    mSeekBar.setMax(duration);
                    String timesum=format.format(duration);
                    mTime.setText(""+timesum);
                    break;
                case Config.MUSIC_SEEK_TO:
                    int currentTime=intent.getIntExtra("currtTime",0);
                    mSeekBar.setProgress(currentTime);
                    String time=format.format(currentTime);
                    mNowTime.setText(""+time);
                    break;
            }
        }
    }
}

这里写图片描述

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值