Android 编程案例-本地音乐播放器源码及使用注意事项

Android 编程案例-本地音乐播放器源码及使用注意事项,第1张

概述说一下代码在用的时候注意事项以及在运行的时候可能遇到的问题:首先代码可以在创建相应文件后直接复制,这个案例用到了RecyclerView,所以需要先添加依赖。添加下面两个:implementation‘com.android.support:recyclerview-v7:27.1.1′implementation‘com.android.support:

说一下代码在用的时候注意事项以及在运行的时候可能遇到的问题:

首先代码可以在创建相应文件后直接复制,这个案例用到了RecyclerVIEw,所以需要先添加依赖。添加下面两个:

implementation ‘com.androID.support:recyclervIEw-v7:27.1.1′implementation ‘com.androID.support:cardvIEw-v7:27.1.1′

具体版本看自己的软件。
一定要在AndroIDManifest.xml加上:

<manifest xmlns:androID=”http://schemas.androID.com/apk/res/androID”/>

下面代码部分也给出了。

接下来说一下运行时的问题:
(1)开发本项目最大的问题在于API版本问题,这也是AndroID开发中最头疼的问题,在遇到问题的时候一定要查看下自己的版本。
(2)在模拟器上打开项目时为空白列表,原因在于模拟器没有音乐文件,可以先利用模拟器下载音乐文件,之后再打开就能显示了 。下载文件的时候不要直接将文件从电脑拖入模拟器,虽然有文件,但是不被应用识别,我在运行的时候就遇到了这个问题,音乐文件最好从网上下载。
(3)如果运行时模拟器不能打开app,报下面错误:

java.lang.SecurityException: Permission Denial: reading com.androID.provIDers.media.MediaProvIDer uri content://media/external/audio/media from pID=13081, uID=10084 requires androID.permission.READ_EXTERNAL_STORAGE, or grantUriPermission()

一定要确定加入了我上面所说的那行代码,然后打开模拟器设置(settings)找到应用管理(apps&notifications),选择应用权限(APP permissions )找到自己的软件,打开文件读取权限。看下面第一张图,附上两张app运行的截图:


下面的的源代码来自:https://gitee.com/happyanimee/localmusic
这里面有整个项目的文件,本文的主要任务是总结使用时候所遇到的问题以及主要代码供大家学习。里面所用到的图片在文末下载。

activity_main.xml
<?xml version="1.0" enCoding="utf-8"?><relativeLayout xmlns:androID="http://schemas.androID.com/apk/res/androID"    androID:layout_wIDth="match_parent"    androID:layout_height="match_parent"    androID:background="@mipmap/bg2">    <relativeLayout        androID:layout_wIDth="match_parent"        androID:layout_height="70dp"        androID:layout_alignParentBottom="true"        androID:ID="@+ID/local_music_bottomlayout"        androID:background="#33EEEEEE">        <ImageVIEw            androID:layout_wIDth="match_parent"            androID:layout_height="0.5dp"            androID:background="#9933FA"/>        <ImageVIEw            androID:layout_wIDth="60dp"            androID:layout_height="60dp"            androID:src="@mipmap/icon_song"            androID:layout_centerVertical="true"            androID:background="@mipmap/a1"            androID:layout_marginleft="10dp"            androID:ID="@+ID/local_music_bottom_iv_icon"/>        <TextVIEw            androID:ID="@+ID/local_music_bottom_tv_song"            androID:layout_wIDth="wrap_content"            androID:layout_height="wrap_content"            androID:text=""            androID:layout_toRightOf="@ID/local_music_bottom_iv_icon"            androID:layout_margintop="10dp"            androID:layout_marginleft="10dp"            androID:textSize="16sp"            androID:textStyle="bold"/>        <TextVIEw            androID:ID="@+ID/local_music_bottom_tv_singer"            androID:layout_wIDth="wrap_content"            androID:layout_height="wrap_content"            androID:text=""            androID:textSize="12sp"            androID:layout_below="@ID/local_music_bottom_tv_song"            androID:layout_alignleft="@ID/local_music_bottom_tv_song"            androID:layout_margintop="10dp"/>        <ImageVIEw            androID:ID="@+ID/local_music_bottom_iv_next"            androID:layout_wIDth="wrap_content"            androID:layout_height="wrap_content"            androID:layout_centerVertical="true"            androID:src="@mipmap/icon_next"            androID:layout_alignParentRight="true"            androID:layout_marginRight="10dp"/>        <ImageVIEw            androID:ID="@+ID/local_music_bottom_iv_play"            androID:layout_wIDth="wrap_content"            androID:layout_height="wrap_content"            androID:layout_centerVertical="true"            androID:src="@mipmap/icon_play"            androID:layout_toleftOf="@ID/local_music_bottom_iv_next"            androID:layout_marginRight="20dp"/>        <ImageVIEw            androID:ID="@+ID/local_music_bottom_iv_last"            androID:layout_wIDth="wrap_content"            androID:layout_height="wrap_content"            androID:layout_centerVertical="true"            androID:src="@mipmap/icon_last"            androID:layout_toleftOf="@ID/local_music_bottom_iv_play"            androID:layout_marginRight="20dp"/>    </relativeLayout><androID.support.v7.Widget.RecyclerVIEw    androID:ID="@+ID/local_music_rv"    androID:layout_wIDth="match_parent"    androID:layout_height="match_parent"    androID:layout_above="@ID/local_music_bottomlayout"></androID.support.v7.Widget.RecyclerVIEw></relativeLayout>
item_local_music.xml
<?xml version="1.0" enCoding="utf-8"?><androID.support.v7.Widget.CardVIEw    xmlns:androID="http://schemas.androID.com/apk/res/androID"    xmlns:app="http://schemas.androID.com/apk/res-auto"    androID:layout_wIDth="match_parent"    androID:layout_height="wrap_content"    androID:layout_marginRight="10dp"    androID:layout_marginleft="10dp"    androID:layout_margintop="10dp"    app:contentpadding="10dp"    app:cardCornerRadius="10dp"    app:cardElevation="1dp"    app:cardBackgroundcolor="@color/colorPink">    <relativeLayout        androID:layout_wIDth="match_parent"        androID:layout_height="wrap_content">        <TextVIEw            androID:ID="@+ID/item_local_music_num"            androID:layout_wIDth="wrap_content"            androID:layout_height="wrap_content"            androID:text="1"            androID:layout_centerVertical="true"            androID:textSize="24sp"            androID:textStyle="bold"/>        <TextVIEw            androID:ID="@+ID/item_local_music_song"            androID:layout_wIDth="wrap_content"            androID:layout_height="wrap_content"            androID:text=""            androID:textSize="18sp"            androID:textStyle="bold"            androID:layout_toRightOf="@ID/item_local_music_num"            androID:singleline="true"            androID:layout_marginleft="20dp"/>        <TextVIEw            androID:ID="@+ID/item_local_music_singer"            androID:layout_wIDth="wrap_content"            androID:layout_height="wrap_content"            androID:text=""            androID:layout_below="@ID/item_local_music_song"            androID:layout_alignleft="@ID/item_local_music_song"            androID:layout_margintop="10dp"            androID:textSize="14sp"            androID:textcolor="#888"/>        <TextVIEw            androID:ID="@+ID/item_local_music_line"            androID:layout_wIDth="2dp"            androID:layout_height="18dp"            androID:background="#888"            androID:layout_toRightOf="@ID/item_local_music_singer"            androID:layout_marginleft="10dp"            androID:layout_marginRight="10dp"            androID:layout_aligntop="@ID/item_local_music_singer"/>        <TextVIEw            androID:ID="@+ID/item_local_music_album"            androID:layout_wIDth="wrap_content"            androID:layout_height="wrap_content"            androID:text=""            androID:layout_toRightOf="@ID/item_local_music_line"            androID:layout_aligntop="@ID/item_local_music_singer"            androID:textSize="14sp"            androID:textcolor="#888"            androID:ellipsize="end"            androID:singleline="true"/>        <TextVIEw            androID:ID="@+ID/item_local_music_durtion"            androID:layout_wIDth="wrap_content"            androID:layout_height="wrap_content"            androID:layout_below="@ID/item_local_music_singer"            androID:layout_alignParentRight="true"            androID:text=""            androID:textSize="14sp"            androID:textcolor="#888"/>    </relativeLayout></androID.support.v7.Widget.CardVIEw>
MainActivity.java
import androID.content.ContentResolver;import androID.database.Cursor;import androID.graphics.Bitmap;import androID.graphics.BitmapFactory;import androID.media.MediaPlayer;import androID.net.Uri;import androID.provIDer.MediaStore;import androID.support.v7.app.AppCompatActivity;import androID.os.Bundle;import androID.support.v7.Widget.linearlayoutmanager;import androID.support.v7.Widget.RecyclerVIEw;import androID.util.Log;import androID.vIEw.VIEw;import androID.Widget.ImageVIEw;import androID.Widget.TextVIEw;import androID.Widget.Toast;import java.io.IOException;import java.text.SimpleDateFormat;import java.util.ArrayList;import java.util.Date;import java.util.List;public class MainActivity extends AppCompatActivity implements VIEw.OnClickListener{    ImageVIEw nextIv,playIv,lastIv,albumIv;    TextVIEw singerTv,songTv;    RecyclerVIEw musicRv;    //    数据源    List<LocalMusicBean>mDatas;    private LocalMusicAdapter adapter;    //    记录当前正在播放的音乐的位置    int currnetPlayposition = -1;    //    记录暂停音乐时进度条的位置    int currentPausepositionInSong = 0;    MediaPlayer mediaPlayer;    @OverrIDe    protected voID onCreate(Bundle savedInstanceState) {        super.onCreate(savedInstanceState);        setContentVIEw(R.layout.activity_main);        initVIEw();        mediaPlayer = new MediaPlayer();        mDatas = new ArrayList<>();//     创建适配器对象        adapter = new LocalMusicAdapter(this, mDatas);        musicRv.setAdapter(adapter);//        设置布局管理器        linearlayoutmanager layoutManager = new linearlayoutmanager(this, linearlayoutmanager.VERTICAL, false);        musicRv.setLayoutManager(layoutManager);//        加载本地数据源        loadLocalMusicdata();//        设置每一项的点击事件        setEventListener();    }    private voID setEventListener() {        /* 设置每一项的点击事件*/        adapter.setonItemClickListener(new LocalMusicAdapter.OnItemClickListener() {            @OverrIDe            public voID OnItemClick(VIEw vIEw, int position) {                currnetPlayposition = position;                LocalMusicBean musicBean = mDatas.get(position);                playMusicInMusicBean(musicBean);            }        });    }    public voID playMusicInMusicBean(LocalMusicBean musicBean) {        /*根据传入对象播放音乐*/        //设置底部显示的歌手名称和歌曲名        singerTv.setText(musicBean.getSinger());        songTv.setText(musicBean.getSong());        stopMusic();//                重置多媒体播放器        mediaPlayer.reset();//                设置新的播放路径        try {            mediaPlayer.setDataSource(musicBean.getPath());            String albumart = musicBean.getalbumart();            Log.i("lsh123", "playMusicInMusicBean: albumpath=="+albumart);            Bitmap bm = BitmapFactory.decodefile(albumart);            Log.i("lsh123", "playMusicInMusicBean: bm=="+bm);            albumIv.setimageBitmap(bm);            playMusic();        } catch (IOException e) {            e.printstacktrace();        }    }    /*     * 点击播放按钮播放音乐,或者暂停从新播放     * 播放音乐有两种情况:     * 1.从暂停到播放     * 2.从停止到播放     * */    private voID playMusic() {        /* 播放音乐的函数*/        if (mediaPlayer!=null&&!mediaPlayer.isPlaying()) {            if (currentPausepositionInSong == 0) {                try {                    mediaPlayer.prepare();                    mediaPlayer.start();                } catch (IOException e) {                    e.printstacktrace();                }            }else{//                从暂停到播放                mediaPlayer.seekTo(currentPausepositionInSong);                mediaPlayer.start();            }            playIv.setimageResource(R.mipmap.icon_pause);        }    }    private voID pauseMusic() {        /* 暂停音乐的函数*/        if (mediaPlayer!=null&&mediaPlayer.isPlaying()) {            currentPausepositionInSong = mediaPlayer.getCurrentposition();            mediaPlayer.pause();            playIv.setimageResource(R.mipmap.icon_play);        }    }    private voID stopMusic() {        /* 停止音乐的函数*/        if (mediaPlayer!=null) {            currentPausepositionInSong = 0;            mediaPlayer.pause();            mediaPlayer.seekTo(0);            mediaPlayer.stop();            playIv.setimageResource(R.mipmap.icon_play);        }    }    @OverrIDe    protected voID onDestroy() {        super.onDestroy();        stopMusic();    }    private voID loadLocalMusicdata() {        /* 加载本地存储当中的音乐mp3文件到集合当中*///        1.获取ContentResolver对象        ContentResolver resolver = getContentResolver();//        2.获取本地音乐存储的Uri地址        Uri uri = MediaStore.Audio.Media.EXTERNAL_CONTENT_URI;//        3 开始查询地址        Cursor cursor = resolver.query(uri, null, null, null, null);//        4.遍历Cursor        int ID = 0;        while (cursor.movetoNext()) {            String song = cursor.getString(cursor.getColumnIndex(MediaStore.Audio.Media.Title));            String singer = cursor.getString(cursor.getColumnIndex(MediaStore.Audio.Media.ARTIST));            String album = cursor.getString(cursor.getColumnIndex(MediaStore.Audio.Media.ALBUM));            ID++;            String sID = String.valueOf(ID);            String path = cursor.getString(cursor.getColumnIndex(MediaStore.Audio.Media.DATA));            long duration = cursor.getLong(cursor.getColumnIndex(MediaStore.Audio.Media.DURATION));            SimpleDateFormat sdf = new SimpleDateFormat("mm:ss");            String time = sdf.format(new Date(duration));//          获取专辑图片主要是通过album_ID进行查询            String album_ID = cursor.getString(cursor.getColumnIndex(MediaStore.Audio.Media.ALBUM_ID));            String albumart = getalbumart(album_ID);//            将一行当中的数据封装到对象当中            LocalMusicBean bean = new LocalMusicBean(sID, song, singer, album, time, path,albumart);            mDatas.add(bean);        }//        数据源变化,提示适配器更新        adapter.notifyDataSetChanged();    }    private String getalbumart(String album_ID) {        String mUriAlbums = "content://media/external/audio/albums";        String[] projection = new String[]{"album_art"};        Cursor cur = this.getContentResolver().query(                Uri.parse(mUriAlbums + "/" + album_ID),                projection, null, null, null);        String album_art = null;        if (cur.getCount() > 0 && cur.getColumnCount() > 0) {            cur.movetoNext();            album_art = cur.getString(0);        }        cur.close();        cur = null;        return album_art;    }    private voID initVIEw() {        /* 初始化控件的函数*/        nextIv = findVIEwByID(R.ID.local_music_bottom_iv_next);        playIv = findVIEwByID(R.ID.local_music_bottom_iv_play);        lastIv = findVIEwByID(R.ID.local_music_bottom_iv_last);        albumIv = findVIEwByID(R.ID.local_music_bottom_iv_icon);        singerTv = findVIEwByID(R.ID.local_music_bottom_tv_singer);        songTv = findVIEwByID(R.ID.local_music_bottom_tv_song);        musicRv = findVIEwByID(R.ID.local_music_rv);        nextIv.setonClickListener(this);        lastIv.setonClickListener(this);        playIv.setonClickListener(this);    }    @OverrIDe    public voID onClick(VIEw v) {        switch (v.getID()) {            case R.ID.local_music_bottom_iv_last:                if (currnetPlayposition ==0) {                    Toast.makeText(this,"已经是第一首了,没有上一曲!",Toast.LENGTH_SHORT).show();                    return;                }                currnetPlayposition = currnetPlayposition-1;                LocalMusicBean lastBean = mDatas.get(currnetPlayposition);                playMusicInMusicBean(lastBean);                break;            case R.ID.local_music_bottom_iv_next:                if (currnetPlayposition ==mDatas.size()-1) {                    Toast.makeText(this,"已经是最后一首了,没有下一曲!",Toast.LENGTH_SHORT).show();                    return;                }                currnetPlayposition = currnetPlayposition+1;                LocalMusicBean nextBean = mDatas.get(currnetPlayposition);                playMusicInMusicBean(nextBean);                break;            case R.ID.local_music_bottom_iv_play:                if (currnetPlayposition == -1) {//                    并没有选中要播放的音乐                    Toast.makeText(this,"请选择想要播放的音乐",Toast.LENGTH_SHORT).show();                    return;                }                if (mediaPlayer.isPlaying()) {//                    此时处于播放状态,需要暂停音乐                    pauseMusic();                }else {//                    此时没有播放音乐,点击开始播放音乐                    playMusic();                }                break;        }    }}
LocalMusicBean.java
public class LocalMusicBean {    private String ID; //歌曲ID    private String song; //歌曲名称    private String singer; //歌手名称    private String album; //专辑名称    private String duration; //歌曲时长    private String path; //歌曲路径    private String albumart;  //专辑地址    public LocalMusicBean() {    }    public LocalMusicBean(String ID, String song, String singer, String album, String duration, String path,String albumart) {        this.ID = ID;        this.song = song;        this.singer = singer;        this.album = album;        this.duration = duration;        this.path = path;        this.albumart = albumart;    }    public String getalbumart() {        return albumart;    }    public voID setalbumart(String albumart) {        this.albumart = albumart;    }    public String getID() {        return ID;    }    public voID setID(String ID) {        this.ID = ID;    }    public String getSong() {        return song;    }    public voID setSong(String song) {        this.song = song;    }    public String getSinger() {        return singer;    }    public voID setSinger(String singer) {        this.singer = singer;    }    public String getAlbum() {        return album;    }    public voID setAlbum(String album) {        this.album = album;    }    public String getDuration() {        return duration;    }    public voID setDuration(String duration) {        this.duration = duration;    }    public String getPath() {        return path;    }    public voID setPath(String path) {        this.path = path;    }}
LocalMusicAdapter.java
import androID.content.Context;        import androID.support.annotation.NonNull;        import androID.support.v7.Widget.RecyclerVIEw;        import androID.vIEw.LayoutInflater;        import androID.vIEw.VIEw;        import androID.vIEw.VIEwGroup;        import androID.Widget.TextVIEw;        import java.util.List;public class LocalMusicAdapter extends RecyclerVIEw.Adapter<LocalMusicAdapter.LocalMusicVIEwHolder>{    Context context;    List<LocalMusicBean>mDatas;    OnItemClickListener onItemClickListener;    public voID setonItemClickListener(OnItemClickListener onItemClickListener) {        this.onItemClickListener = onItemClickListener;    }    public interface OnItemClickListener{        public voID OnItemClick(VIEw vIEw,int position);    }    public LocalMusicAdapter(Context context, List<LocalMusicBean> mDatas) {        this.context = context;        this.mDatas = mDatas;    }    @NonNull    @OverrIDe    public LocalMusicVIEwHolder onCreateVIEwHolder(@NonNull VIEwGroup parent, int vIEwType) {        VIEw vIEw = LayoutInflater.from(context).inflate(R.layout.item_local_music,parent,false);        LocalMusicVIEwHolder holder = new LocalMusicVIEwHolder(vIEw);        return holder;    }    @OverrIDe    public voID onBindVIEwHolder(@NonNull LocalMusicVIEwHolder holder, final int position) {        LocalMusicBean musicBean = mDatas.get(position);        holder.IDTv.setText(musicBean.getID());        holder.songTv.setText(musicBean.getSong());        holder.singerTv.setText(musicBean.getSinger());        holder.albumTv.setText(musicBean.getAlbum());        holder.timeTv.setText(musicBean.getDuration());        holder.itemVIEw.setonClickListener(new VIEw.OnClickListener() {            @OverrIDe            public voID onClick(VIEw v) {                onItemClickListener.OnItemClick(v,position);            }        });    }    @OverrIDe    public int getItemCount() {        return mDatas.size();    }    class LocalMusicVIEwHolder extends RecyclerVIEw.VIEwHolder{        TextVIEw IDTv,songTv,singerTv,albumTv,timeTv;        public LocalMusicVIEwHolder(VIEw itemVIEw) {            super(itemVIEw);            IDTv = itemVIEw.findVIEwByID(R.ID.item_local_music_num);            songTv = itemVIEw.findVIEwByID(R.ID.item_local_music_song);            singerTv = itemVIEw.findVIEwByID(R.ID.item_local_music_singer);            albumTv = itemVIEw.findVIEwByID(R.ID.item_local_music_album);            timeTv = itemVIEw.findVIEwByID(R.ID.item_local_music_durtion);        }    }}
AndroIDManifest.xml
<?xml version="1.0" enCoding="utf-8"?><manifest xmlns:androID="http://schemas.androID.com/apk/res/androID"    package="com.example.a33119.music">    <uses-permission androID:name="androID.permission.WRITE_EXTERNAL_STORAGE"/>    <application        androID:allowBackup="true"        androID:icon="@mipmap/ic_launcher"        androID:label="@string/app_name"        androID:roundIcon="@mipmap/ic_launcher_round"        androID:supportsRtl="true"        androID:theme="@style/Apptheme">        <activity androID:name=".MainActivity">            <intent-filter>                <action androID:name="androID.intent.action.MAIN" />                <category androID:name="androID.intent.category.LAUNCHER" />            </intent-filter>        </activity>    </application></manifest>

打包后apk:本地音乐播放器APP

总结

以上是内存溢出为你收集整理的Android 编程案例-本地音乐播放器源码及使用注意事项全部内容,希望文章能够帮你解决Android 编程案例-本地音乐播放器源码及使用注意事项所遇到的程序开发问题。

如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。

欢迎分享,转载请注明来源:内存溢出

原文地址:https://54852.com/web/1060890.html

(0)
打赏 微信扫一扫微信扫一扫 支付宝扫一扫支付宝扫一扫
上一篇 2022-05-25
下一篇2022-05-25

发表评论

登录后才能评论

评论列表(0条)

    保存