音乐和视频播放器




<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="db.lanxing.damexshixu.ui.frament.BlankFragment2">

    <android.support.v7.widget.RecyclerView
        android:id="@+id/rcw2"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_weight="1" />
    <TextView
        android:id="@+id/name"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_weight="9" />
    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_weight="9"
        android:orientation="horizontal">

        <SeekBar
            android:id="@+id/sbr"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:layout_weight="1" />

        <TextView
            android:id="@+id/time"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:layout_weight="5" />
    </LinearLayout>

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_weight="9"
        android:orientation="horizontal">

        <ImageButton
            android:id="@+id/back"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:layout_weight="1"
            android:background="@drawable/musicplaybar_back" />

        <ImageButton
            android:id="@+id/pause"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:layout_weight="1"
            android:background="@drawable/stat_notify_musicplayer" />

        <ImageButton
            android:id="@+id/play"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:layout_weight="1"
            android:visibility="gone"
            android:background="@drawable/musicplaybar_stop" />

        <ImageButton
            android:id="@+id/next"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:layout_weight="1"
            android:background="@drawable/musicplaybar_next" />

        <ImageButton
            android:id="@+id/mu"
            android:background="@drawable/noconnect_music"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:layout_weight="1" />


    </LinearLayout>
</LinearLayout>
//音乐播放器,只要一开始播放就开始发送handle,开始不停更新,直到音乐播完

package db.lanxing.damexshixu.ui.frament;

import android.Manifest;
import android.content.Intent;
import android.database.Cursor;
import android.media.MediaPlayer;
import android.os.Bundle;
import android.os.Handler;
import android.provider.MediaStore;
import android.support.annotation.NonNull;
import android.support.v4.app.Fragment;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.StaggeredGridLayoutManager;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageButton;
import android.widget.SeekBar;
import android.widget.TextView;

import com.chad.library.adapter.base.BaseQuickAdapter;

import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import butterknife.Unbinder;
import db.lanxing.damexshixu.R;
import db.lanxing.damexshixu.adapter.MyMusicAdapter;
import db.lanxing.damexshixu.adapter.MyRecAdapter;
import db.lanxing.damexshixu.data.Musics;
import db.lanxing.damexshixu.ui.activity.ImgActivity;
import permissions.dispatcher.NeedsPermission;
import permissions.dispatcher.RuntimePermissions;

/**
 * A simple {@link Fragment} subclass.
 */
@RuntimePermissions
public class BlankFragment2 extends Fragment {
    ArrayList<Musics> list = new ArrayList<>();
    SimpleDateFormat format = new SimpleDateFormat("mm:ss");
    @BindView(R.id.name)
    TextView name;
    Unbinder unbinder1;
    private Handler handler = new Handler();
    private MediaPlayer player;
    Runnable runnable = new Runnable() {
        @Override
        public void run() {

            sbr.setMax(player.getDuration());
            sbr.setProgress(player.getCurrentPosition());
            time.setText(format.format(player.getCurrentPosition()));
            handler.postDelayed(runnable, 100);//重复更新
        }
    };
    @BindView(R.id.rcw2)
    RecyclerView rcw2;
    @BindView(R.id.sbr)
    SeekBar sbr;
    @BindView(R.id.time)
    TextView time;
    @BindView(R.id.back)
    ImageButton back;
    @BindView(R.id.pause)
    ImageButton pause;
    @BindView(R.id.play)
    ImageButton play;
    @BindView(R.id.next)
    ImageButton next;
    @BindView(R.id.mu)
    ImageButton mu;
    Unbinder unbinder;
    private View inflate;
    private int bj;
    private MyMusicAdapter adapter;


    public BlankFragment2() {
        // Required empty public constructor
    }


    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        inflate = inflater.inflate(R.layout.fragment_blank_fragment2, container, false);
        unbinder1 = ButterKnife.bind(this, inflate);
        BlankFragment2PermissionsDispatcher.myMp3WithCheck(this);

        initListener();

        return inflate;
    }

    private void initListener() {
        rcw2.setLayoutManager(new StaggeredGridLayoutManager(1, StaggeredGridLayoutManager.VERTICAL));
        adapter = new MyMusicAdapter(R.layout.music, list);
        rcw2.setAdapter(adapter);
        adapter.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
                bj = position;
                plays(position);
            }
        });
        adapter.setOnItemLongClickListener(new BaseQuickAdapter.OnItemLongClickListener() {

            private Intent intent;

            @Override
            public boolean onItemLongClick(BaseQuickAdapter adapter, View view, int position) {
                intent = new Intent(getActivity(), ImgActivity.class);
                intent.putExtra("img",list.get(position).getImgdata());
                startActivity(intent);
                return true;
            }
        });
        sbr.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) {
                player.seekTo(sbr.getProgress());
            }
        });
    }

    @NeedsPermission({Manifest.permission.READ_EXTERNAL_STORAGE, Manifest.permission.WRITE_EXTERNAL_STORAGE})
    void myMp3() {
        Cursor query = getActivity().getContentResolver().query(MediaStore.Audio.Media.EXTERNAL_CONTENT_URI,
                null, null, null, MediaStore.Audio.Media.DEFAULT_SORT_ORDER);
        Cursor queryImg = getActivity().getContentResolver().query(MediaStore.Images.Media.EXTERNAL_CONTENT_URI,
                null, null, null, MediaStore.Images.Media.DEFAULT_SORT_ORDER);
        if (query.moveToFirst() && queryImg.moveToFirst()) {
            while (!query.isAfterLast() && !queryImg.isAfterLast()) {
                String title = query.getString(query.getColumnIndex(MediaStore.Audio.Media.TITLE));
                String album = query.getString(query.getColumnIndex(MediaStore.Audio.Media.ALBUM));

                String artist = query.getString(query.getColumnIndex(MediaStore.Audio.Media.ARTIST));
                String data = query.getString(query.getColumnIndex(MediaStore.Audio.Media.DATA));
                int duration = query.getInt(query.getColumnIndex(MediaStore.Audio.Media.DURATION));
                String id = query.getString(query.getColumnIndex(MediaStore.Audio.Media._ID));
                long size = query.getLong(query.getColumnIndex(MediaStore.Audio.Media.SIZE));
                String img = queryImg.getString(queryImg.getColumnIndex(MediaStore.Images.Media.DATA));
                if (size > 1024 * 800) {
                    list.add(new Musics(id, title, artist, data, img, album, duration));
                }
                query.moveToNext();
                queryImg.moveToNext();
            }

        }
    }

    private void getStart(int position) {
        try {

            player.setDataSource(list.get(position).getData());//设置路径
            player.prepare();//准备播放
            name.setText(list.get(position).getTitle());//设置歌名
            time.setText(format.format(player.getDuration()));//设置总时间
            player.setLooping(true);//设置重复播放
            player.start();//开始播放

            handler.post(runnable);//开始更新数据
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        BlankFragment2PermissionsDispatcher.onRequestPermissionsResult(this, requestCode, grantResults);
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        unbinder1.unbind();
    }

    @OnClick({R.id.back, R.id.pause, R.id.play, R.id.next, R.id.mu})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.back:
                if (bj == 0) {
                    bj = list.size() - 1;
                } else {
                    --bj;
                }

                plays(bj);
                break;
            case R.id.pause:
                getSS();
                break;
            case R.id.play:
                break;
            case R.id.next:
                if (bj == list.size() - 1) {
                    bj = 0;
                } else {
                    --bj;
                }
                plays(bj);
                break;
            case R.id.mu:
                break;
        }
    }

    private void getSS() {
        if (player == null) {
            player = new MediaPlayer();
            getStart(bj);
        } else {

            if (player.isPlaying()) {
                player.pause();

            } else {
                player.start();

            }
        }
    }


    private void plays(int position) {
        if (player == null) {
            player = new MediaPlayer();

        } else {
            player.stop();
            player = new MediaPlayer();
//            player.reset();
        }
        getStart(position);
    }
}


<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context="db.lanxing.damexshixu.ui.activity.VideoActivity">
<VideoView
    android:id="@+id/vi"
    android:layout_width="match_parent"
    android:layout_height="match_parent" />
</android.support.constraint.ConstraintLayout>


//视频播放器有自带的控制器

package db.lanxing.damexshixu.ui.activity;

import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.widget.MediaController;
import android.widget.VideoView;

import butterknife.BindView;
import butterknife.ButterKnife;
import db.lanxing.damexshixu.R;

public class VideoActivity extends AppCompatActivity {

    @BindView(R.id.vi)
    VideoView vi;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_video);
        ButterKnife.bind(this);
        initView();
    }
    private void initView() {
        vi = (VideoView) findViewById(R.id.vi);
        //给视频设置控制器
        vi.setMediaController(new MediaController(this));
        //给视频设置路径
        vi.setVideoPath(getIntent().getStringExtra("video"));
        vi.start();
        vi.requestFocus();//让视频自动获取焦点

    }
}


猜你喜欢

转载自blog.csdn.net/qq_42120002/article/details/80734060
今日推荐