安卓实训04

一、创建安卓应用

在这里插入图片描述

将MP3音频文件放到存储卡指定位置

在这里插入图片描述

从电脑上添加自己喜欢的MP3音频文件到Music目录
在这里插入图片描述
将图片素材拷贝到Drawable目录
在这里插入图片描述

创建按钮背景图片选择器

在这里插入图片描述

创建暂停一个背景图片选择器按钮

在这里插入图片描述
在这里插入图片描述

播放按钮背景图片选择器

在这里插入图片描述

上一首按钮背景图片选择器

在这里插入图片描述

下一首按钮背景图片选择器

在这里插入图片描述

主布局资源文件

在这里插入图片描述

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout 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"
    android:background="@drawable/background"
    android:orientation="vertical"
    android:padding="20sp"
    tools:context=".ui.MainActivity">
    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="horizontal">
        <ProgressBar
            android:layout_width="100dp"
            android:layout_height="100dp"
            android:id="@+id/pbScanMusic"
            android:visibility="gone"/>
        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:id="@+id/tvScanMusic"
            android:text="@string/scan_music"
            android:textColor="#00BCD4"
            android:textSize="25sp"
            android:visibility="gone"/>

    </LinearLayout>

    <ListView
        android:id="@+id/lvMusicName"
        android:layout_width="match_parent"
        android:layout_height="500dp"
        android:layout_marginBottom="16dp"
        android:layout_weight="8" />

    <TextView
        android:id="@+id/tvMusicName"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_weight="0.5"
        android:textColor="#03A9F4"
        android:textSize="20sp" />

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginTop="10dp"
        android:layout_marginBottom="10dp"
        android:layout_weight="0.5"
        android:gravity="center"
        android:orientation="horizontal">

        <TextView
            android:id="@+id/tvCurrentPosition"
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:textColor="#ff0000" />

        <ProgressBar
            android:id="@+id/pbMusicProgress"
            style="?android:attr/progressBarStyleHorizontal"
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:layout_weight="6" />

        <TextView
            android:id="@+id/tvDuration"
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:textColor="#ff00ff" />
    </LinearLayout>

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_weight="0.5"
        android:gravity="center"
        android:orientation="horizontal">

        <Button
            android:id="@+id/btnPrevious"
            android:layout_width="60dp"
            android:layout_height="50dp"
            android:background="@drawable/previous_button_selector"
            android:onClick="doPrevious" />

        <Button
            android:id="@+id/btnPlayOrPause"
            android:layout_width="60dp"
            android:layout_height="50dp"
            android:background="@drawable/play_button_selector"
            android:onClick="doPlayOrPause" />

        <Button
            android:id="@+id/btnNext"
            android:layout_width="60dp"
            android:layout_height="50dp"
            android:background="@drawable/next_button_selector"
            android:onClick="doNext" />
    </LinearLayout>
</LinearLayout>

在项目清单文件里设置安卓应用的图标

在这里插入图片描述

创建音乐名列表项模板

在这里插入图片描述

字符串资源文件strings.xml

在这里插入图片描述
在这里插入图片描述

创建ui子包,将MainActivity拖进ui子包

在这里插入图片描述
在这里插入图片描述
在这里插入图片描述
在这里插入图片描述

主界面类

package net.tp.sdcard_musicplayer_v04.ui;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;

import android.Manifest;
import android.content.pm.PackageManager;
import android.media.MediaPlayer;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.View;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.ListView;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;

import net.tp.sdcard_musicplayer_v04.R;
import net.tp.sdcard_musicplayer_v04.adapter.MusicAdapter;
import net.tp.sdcard_musicplayer_v04.app.MusicPlayerApplication;
import net.tp.sdcard_musicplayer_v04.entity.Music;

import java.io.File;
import java.io.IOException;
import java.util.List;

/**
 * 功能:基于存储卡音乐播放器V0.4
 * 作者:小滕
 * 日期:2021年01月05日
 */

public class MainActivity extends AppCompatActivity {
    private MediaPlayer mp; // 媒体播放器
    private String musicName; // 音乐文件名
    private TextView tvMusicName; // 音乐名标签
    private Button btnPlayOrPause; // 播放|暂停按钮
    private int currentPosition; // 音乐当前播放位置
    private TextView tvCurrentPosition;//显示当前播放位置的标签
    private TextView tvDuration; //显示音乐播放时长的标签
    private ProgressBar pbMusicProgress;//音乐播放进度条
    private Thread thread;//线程
    private Handler handler;//消息处理器
    private boolean isRunning;//线程循环控制变量
    private ListView lvMusicName;//音乐名列表控件
    private List<Music> musicList;//音乐列表(数据源)
    private MusicAdapter adapter;//音乐适配器
    private  int musicIndex;//音乐索引(表明在音乐列表中位置)
    private MusicPlayerApplication app;//音乐播放器应用程序对象
    private ProgressBar pbScanMusic;//扫描存储卡音乐进度条
    private  TextView tvScanMusic;//扫描存储卡音乐标签(提示用户耐心等待)

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        // 利用布局资源文件设置用户界面
        setContentView(R.layout.activity_main);
        // 通过资源标识符获取控件实例
        lvMusicName=findViewById(R.id.lvMusicName);
        tvMusicName = findViewById(R.id.tvMusicName);
        btnPlayOrPause = findViewById(R.id.btnPlayOrPause);
        tvCurrentPosition = findViewById(R.id.tvCurrentPosition);
        tvDuration = findViewById(R.id.tvDuration);
        pbMusicProgress = findViewById(R.id.pbMusicProgress);
        pbScanMusic=findViewById(R.id.pbScanMusic);
        tvScanMusic=findViewById(R.id.tvScanMusic);
        // 初始化播放器
        mp = new MediaPlayer();

        //获取音乐播放器应用程序对象
        app=(MusicPlayerApplication)getApplication();

        // 定义存储读写权限数组
        String[] PERMISSIONS_STORAGE = {
                Manifest.permission.READ_EXTERNAL_STORAGE,
                Manifest.permission.WRITE_EXTERNAL_STORAGE
        };

        // 检查是否有读权限
         final int permission = ActivityCompat.checkSelfPermission(this, PERMISSIONS_STORAGE[0]);
        // 如果没有授权,那么就请求读权限

        if(permission != PackageManager.PERMISSION_GRANTED) {
            ActivityCompat.requestPermissions(this, PERMISSIONS_STORAGE, 0);
        }
        //启动填充音乐播放列表异步任务
        new FillMusicListTask().execute();

        //创建线程循环控制变量为真
        isRunning =true;
        //创建子线程,定时发送消息
        thread =new Thread(new Runnable() {
            @Override
            public void run() {
                while (isRunning){
                    //向主线发送消息
                    handler.sendEmptyMessage(0x001);
                    try {
                        //让线程睡眠500毫秒
                        Thread.sleep(500);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }

                }
            }
        });
        //启动子线程
        thread.start();
        //创建消息处理器,接收子线程发送的消息
        handler =new Handler(){
            @Override
            public void handleMessage(@NonNull Message msg) {
                super.handleMessage(msg);
                //根据子线程发送的消息进行相应处理
                if (msg.what == 0x001){
                    //判断音乐是否在播放
                    if (mp.isPlaying()){
                        //获取当前播放位置
                        currentPosition =mp.getCurrentPosition();
                        //更新音乐播放进度条的进度值
                        pbMusicProgress.setProgress(currentPosition);
                        //更新当前播放位置标签的内容
                        tvCurrentPosition.setText(app.getFormatTime(currentPosition));
                    }
                }
            }
        };
        //给音乐列表控件注册监听器
        lvMusicName.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                //获取音乐索引
                musicIndex =position;
                //当前播放位置归零
                currentPosition =0;
                try{
                    //调用播放方法
                    play();
                }catch (IOException e){
                    e.printStackTrace();
                }
            }
        });
        //给媒体播放器注册完成注册
        mp.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
            @Override
            public void onCompletion(MediaPlayer mediaPlayer) {
                try {
                    // 切换到下一首
                    nextMusic();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        });

    }

    /**
     * 填充音乐列表异步任务类
     */

    private class FillMusicListTask extends AsyncTask<Void,Integer,Void> {
        /**
         * 耗时工作执行前
         */

        @Override
        protected void onPreExecute() {
            super.onPreExecute();
            //显示扫描音乐进度条
            pbScanMusic.setVisibility(View.VISIBLE);
            //显示扫描音乐标签
            tvScanMusic.setVisibility(View.VISIBLE);
        }

        @Override
        protected Void doInBackground(Void... voids) {
            //获取音乐列表
            musicList =app.getMusicList();
            //故意耗时,要不然扫描太快结束
            for(long i =0; i<2000000000;i++){
            }
            return null;
        }


        @Override
        protected void onPostExecute(Void aVoid) {
            super.onPostExecute(aVoid);
            //隐藏扫描音乐进度条
            pbScanMusic.setVisibility(View.GONE);
            //隐藏扫描音乐标签
            tvScanMusic.setVisibility(View.GONE);

            //判断音乐列表是否有元素
            if (musicList.size() > 0){
                //
                adapter = new MusicAdapter(MainActivity.this,musicList);
                //给音乐列表控件设置适配器
                lvMusicName.setAdapter(adapter);
                //获取当前要播放的音乐名(默认是音乐播放列表的第一首)
                musicName =musicList.get(0).getMusicName();
                //设置音乐名
                tvMusicName.setText("NO." + ( musicIndex +1) +" "+musicName.substring(
                        musicName.lastIndexOf("/")+1,musicName.lastIndexOf(".")));



                try {
                    //设置播放源(完整音乐名 = 音乐目录+音乐名)
                    mp.setDataSource(musicName);
                    //缓冲播放源《从存储卡加载到内存)
                    mp.prepare();
                    //设置当前播放位置标签
                    tvCurrentPosition.setText(app.getFormatTime(mp.getCurrentPosition()));
                    //设置音乐播放时长标签
                    tvDuration.setText(app.getFormatTime(mp.getDuration()));
                    //数字化音乐播放进度条的最大值
                    pbMusicProgress.setMax(mp.getDuration());
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }else {
                //提示用户没有音乐文件
                Toast.makeText(MainActivity.this,"外置存储卡没有音乐文件!",Toast.LENGTH_SHORT).show();
            }

        }
    }
    /**
     * 播放方法
     */
    private void play() throws IOException {
        // 重置媒体播放器
        mp.reset();
        //获取当前播放的音乐名
        musicName =musicList.get(musicIndex).getMusicName();
        //设置音乐名标签内容,去掉扩路径和展名,添加序号
        tvMusicName.setText("NO."+(musicIndex + 1)+" "+musicName.substring(
                musicName.lastIndexOf("/")+1,musicName.lastIndexOf(".")));
        // 设置播放源(完整音乐名 = 音乐目录 + 音乐名)
        mp.setDataSource(musicName);
        // 缓冲播放源(从存储卡加载到内存)
        mp.prepare();
        //设置当前播放位置标签
        tvCurrentPosition.setText(app.getFormatTime(mp.getCurrentPosition()));
        //设置音乐播放时长标签
        tvDuration.setText(app.getFormatTime(mp.getDuration()));
        //数字化音乐播放进度条的最大值
        pbMusicProgress.setMax(mp.getDuration());
        // 定位到暂停时的播放位置
        mp.seekTo(currentPosition);
        // 启动音乐的播放
        mp.start();
        // 按钮图标由【播放】图标切换到【暂停】图标
        btnPlayOrPause.setBackgroundResource(R.drawable.pause_button_selector);

    }
    /**
     * 暂停方法
     */
    private void pause() {
        // 暂停播放
        mp.pause();
        // 保存音乐播放的当前位置
        currentPosition = mp.getCurrentPosition();
        // 按钮图标由【暂停】图标切换到【播放】图标
        btnPlayOrPause.setBackgroundResource(R.drawable.play_button_selector);
    }


    /**
     * 下一首音乐
     */
    private  void nextMusic() throws IOException {
        //更新音乐索引
        if (musicIndex < musicList.size() -1){
            musicIndex++;
        }else {
            musicIndex =0;
        }
        //当前播放位置归零
        currentPosition =0;
        //调用播放方法
        play();
    }

    /**
     * 上一首音乐
     */
    private  void previousMusic() throws IOException {
        //更新音乐索引
        if (musicIndex >0){
            musicIndex--;
        }else {
            musicIndex =musicList.size()-1;
        }
        //当前播放位置归零
        currentPosition =0;
        //调用播放方法
        play();
    }
    /**
     * 播放|暂停按钮单击事件处理方法
     *
     * @param view
     */
    public void doPlayOrPause(View view) throws IOException {
        // 判断音乐是否在播放
        if (mp.isPlaying()) {
            // 暂停音乐
            pause();
        } else {
            // 播放音乐
            play();
        }
    }
    /**
     * 上一首按钮单击事件处理方法
     * @param view
     */

    public void doPrevious(View view) throws IOException{
        previousMusic();

    }
    /**
     * 下一首按钮单击事件处理方法
     * @param  view
     */

    public void doNext(View view)throws IOException{
        nextMusic();

    }
    /**
     * 销毁回调方法,释放资源
     */
    @Override
    protected void onDestroy() {
        super.onDestroy();
        //停止线程
        isRunning =false;

        // 判断音乐是否在播放
        if (mp !=null && mp.isPlaying()) {
            mp.stop();
        }
        // 释放媒体播放器
        mp.release();
        // 销毁媒体播放器
        mp = null;
    }
}

运行结果

在这里插入图片描述

总结

提示:这里对文章进行总结:
例如:以上就是今天要讲的内容,本文仅仅简单介绍了pandas的使用,而pandas提供了大量能使我们快速便捷地处理数据的函数和方法。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值