音乐播放(MediaPlayer,service,receiver,thread)

来源:互联网 发布:网络协议分析题库答案 编辑:程序博客网 时间:2024/05/16 08:12

简单的播放按钮

 @Override    public void onClick(View v) {        MediaPlayer player = new MediaPlayer();        player.reset();        Log.d("", "" + Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_MUSIC).getAbsolutePath());        File musicDir = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_MUSIC);//找到默认的sdcard下MUSIC文件夹中的文件        /*或者这样写         File sdcard =  Environment.getExternalStorageDirectory();        File musicDir = new File("sdcard","/MUSIC");*/        File[] musics = musicDir.listFiles();        try {            player.setDataSource(music[0].getAbsolutePath());//播放第一个文件            player.prepare();            player.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {                @Override                public void onPrepared(MediaPlayer mp) {                    mp.start();                }            });        } catch (IOException e) {            e.printStackTrace();        }    }}

自制简易音乐播放器

1、界面布局

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=".MainActivity">    <ListView        android:id="@+id/listview"        android:layout_width="match_parent"        android:layout_height="match_parent"        android:layout_weight="1"></ListView>    <SeekBar        android:id="@+id/seekbar"        android:layout_width="match_parent"        android:layout_height="wrap_content" />    <TextView        android:id="@+id/textview_all"        android:layout_width="match_parent"        android:layout_height="wrap_content"        android:text="总时长" />    <TextView        android:id="@+id/textview_current"        android:layout_width="match_parent"        android:layout_height="wrap_content"        android:text="当前进度" />    <LinearLayout        android:layout_width="match_parent"        android:layout_height="wrap_content"        android:gravity="center"        android:orientation="horizontal">        <ImageButton            android:id="@+id/button"            android:layout_width="50dp"            android:layout_height="50dp"            android:background="@null"            android:src="@mipmap/play" />//添加一个播放暂停按钮    </LinearLayout></LinearLayout>

这里写图片描述
2、歌曲数据布局

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"    android:layout_width="match_parent"    android:layout_height="match_parent"    android:orientation="horizontal">    <ImageView        android:id="@+id/music_img"        android:layout_width="60dp"        android:layout_height="60dp"        android:src="@mipmap/guangpan"/>    <TextView        android:id="@+id/music_author"        android:layout_width="wrap_content"        android:layout_height="wrap_content"        android:text="作者"        android:layout_marginLeft="20dp"        android:layout_marginRight="20dp"        android:layout_marginTop="20dp"/>    <TextView        android:id="@+id/music_name"        android:layout_width="wrap_content"        android:layout_height="wrap_content"        android:text="歌名"        android:layout_marginTop="20dp"/></LinearLayout>

这里写图片描述

3、写一个adapter实现界面与数据的联系

public class MyMusicAdapter extends BaseAdapter {    private LayoutInflater mFlater;    private File[] mFiles;    public MyMusicAdapter(File[] mFiles, LayoutInflater mFlater) {        this.mFiles = mFiles;        this.mFlater = mFlater;    }    @Override    public int getCount() {        return mFiles.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 (convertView == null) {            vh = new ViewHolder();            convertView = mFlater.inflate(R.layout.item_music, null);            vh.myName = (TextView) convertView.findViewById(R.id.music_name);            vh.musicAuthor = (TextView) convertView.findViewById(R.id.music_author);            vh.musicImg = (ImageView) convertView.findViewById(R.id.music_img);            convertView.setTag(vh);        }        vh = (ViewHolder) convertView.getTag();        vh.myName.setText(mFiles[position].getName());        MediaMetadataRetriever mmr = new MediaMetadataRetriever();//用来得到信息的方法        mmr.setDataSource(mFiles[position].getAbsolutePath());        // 下面得到作者        String author = mmr.extractMetadata(MediaMetadataRetriever.METADATA_KEY_ARTIST);        if (author != null) {            vh.musicAuthor.setText(author);        } else {            vh.musicAuthor.setText("<未知>");        }        //下面是得到音乐的图片        byte[] image = mmr.getEmbeddedPicture();        if (image != null) {            Bitmap bitmap = BitmapFactory.decodeByteArray(image, 0, image.length);            vh.musicImg.setImageBitmap(bitmap);        } else {            vh.musicImg.setImageResource(R.mipmap.guangpan);        }        return convertView;    }    class ViewHolder {        TextView myName;        ImageView musicImg;        TextView musicAuthor;    }}

4、MyService

public class MyService 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", 0);        switch (type) {            case config.START_NEW_MUSIC:                startNewMusic(intent);                break;            case config.SEEK_TO_MUSIC:                if (player != null) {                    int progress = intent.getIntExtra("progress", 0);                    player.seekTo(progress);//播放到滚动到的位置                }                break;            case config.MUSIC_PLAY:                if(player!=null&&player.isPlaying()){                    player.start();                }                break;            case config.MUSIC_PAUSE:                if(player!=null&&player.isPlaying()){                    player.pause();                }                break;            case config.MUSIC_CONTINUE:                if(player!=null){                    player.start();                    MusicPlayThread thread = new MusicPlayThread();                    thread.start();                }else{                    startNewMusic(intent);                }                break;        }        return super.onStartCommand(intent, flags, startId);    }    private void startNewMusic(Intent intent) {        String musicPath = intent.getStringExtra("musicName");        if (player == null) {            player = new MediaPlayer();        }        player.reset();        try {            player.setDataSource(musicPath);            player.prepare();            player.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {                @Override                public void onPrepared(MediaPlayer mp) {                    mp.start();                    int duration = player.getDuration();//得到总的播放时间                    Intent intent = new Intent("play.music");                    intent.putExtra("type", config.START_NEW_MUSIC);                    intent.putExtra("duration", duration);                    sendBroadcast(intent);                    MusicPlayThread thread = new MusicPlayThread();                    thread.start();                }            });        } catch (IOException e) {            e.printStackTrace();        }    }    @Override    public void onDestroy() {        super.onDestroy();    }    class MusicPlayThread extends Thread {        @Override        public void run() {            while (player.isPlaying()) {                int time = player.getCurrentPosition();//得到当前的播放位置                Intent intent = new Intent("play.music");                intent.putExtra("type", config.SEEK_TO_MUSIC);                intent.putExtra("duration", time);                sendBroadcast(intent);                try {                    Thread.sleep(1000);                } catch (InterruptedException e) {                    e.printStackTrace();                }            }        }    }}

5、activity

public class MainActivity extends Activity {    private ListView mListview;    private File[] mMusics;    private LayoutInflater mFlater;    private MyMusicAdapter mAdapter;    private SeekBar mSeekBar;    private ImageButton mButton;    private MyReceiver receiver;    private TextView mTimeAll;    private TextView mTimeCurrent;    private boolean isPlaying;    @TargetApi(Build.VERSION_CODES.FROYO)    @Override    protected void onCreate(Bundle savedInstanceState) {        super.onCreate(savedInstanceState);        setContentView(R.layout.activity_main);        mListview = (ListView) findViewById(R.id.listview);        mSeekBar = (SeekBar) findViewById(R.id.seekbar);        mTimeAll = (TextView) findViewById(R.id.textview_all);        mTimeCurrent = (TextView) findViewById(R.id.textview_current);        mButton = (ImageButton) findViewById(R.id.button);//注册receiver        receiver = new MyReceiver();        IntentFilter filter = new IntentFilter();        filter.addAction("play.music");        registerReceiver(receiver, filter);//去找sdcard下的music文件夹中的文件        File mMusicsdir = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_MUSIC);        mMusics = mMusicsdir.listFiles();        mFlater = getLayoutInflater();        mAdapter = new MyMusicAdapter(mMusics, mFlater);        mListview.setAdapter(mAdapter);        mListview.setOnItemClickListener(new AdapterView.OnItemClickListener() {            //选择歌曲是启动服务,播放此音乐            @Override            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {                Intent intent = new Intent(getApplicationContext(), MyService.class);                intent.putExtra("musicName", mMusics[position].getAbsolutePath());                startService(intent);                mButton.setImageResource(R.mipmap.pause);                isPlaying = true;            }        });        mButton.setOnClickListener(new View.OnClickListener() {            @Override            public void onClick(View v) {//按钮点击事件                if(isPlaying){//点击时如果正在播放就暂停                    Intent intent = new Intent(getApplicationContext(), MyService.class);                    intent.putExtra("type", config.MUSIC_PAUSE);                    startService(intent);                    mButton.setImageResource(R.mipmap.play);                }else{                    Intent intent = new Intent(getApplicationContext(), MyService.class);                    intent.putExtra("type", config.MUSIC_CONTINUE);                    intent.putExtra("musicName", mMusics[0].getAbsolutePath());//没有播放是点击就播放,如果没有选择歌曲,默认播放第一首                    startService(intent);                    mButton.setImageResource(R.mipmap.pause);                }                isPlaying=!isPlaying;            }        });        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(), MyService.class);                intent.putExtra("type", config.SEEK_TO_MUSIC);                intent.putExtra("progress", seekBar.getProgress());                startService(intent);            }        });    }    class MyReceiver extends BroadcastReceiver {        @Override        public void onReceive(Context context, Intent intent) {            int type = intent.getIntExtra("type", 1);            switch (type) {                case config.START_NEW_MUSIC:                    int duration = intent.getIntExtra("duration", 0);                    mTimeAll.setText("总时长: " + duration / 1000 + "秒");                    mSeekBar.setMax(duration);                    break;                case config.SEEK_TO_MUSIC:                    int currentTime = intent.getIntExtra("duration", 0);                    mTimeCurrent.setText("进度: " + currentTime / 1000);                    mSeekBar.setProgress(currentTime);                    break;            }        }    }    @Override    protected void onDestroy() {        super.onDestroy();        unregisterReceiver(receiver);    }}
0 0
原创粉丝点击