Android实现简单的音乐播放器

本文实例为大家分享了Android实现简单音乐播放器的具体代码,供大家参考,具体内容如下

1.制作一个简易的音乐播放器

使用软件:Android studio + jdk1.8 + Gradle6.5(其他版本也可以)

2.activity_main.xml文件(主页面的编写)

先看一下示意图再来排版(音乐板块的模型看的是某云)

分3个部分来看,第一个是音乐的标题,就是Sky_High、No Copyright Sounds和那个圆形的可以转动的图标。

<ImageView
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:scaleType="fitXY"
    android:src="@mipmap/music_background" />  //这里是配置背景的,就是后面的青蓝色板块
 
<TextView
    android:id="@+id/tv_song_name"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:layout_marginTop="32dp"
    android:gravity="center_horizontal"
    android:text="Sky_High"
    android:textAlignment="center"
    android:textSize="24sp" />  //这是第一行Sky_High的
 
<TextView
    android:id="@+id/tv_song_singer"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:layout_below="@id/tv_song_name"
    android:gravity="center_horizontal"
    android:text="No Copyright Sounds"
    android:textAlignment="center"
    android:textSize="18sp" />  //这是第二行No Copyright Sounds
 
<ImageView
    android:id="@+id/iv_disk"
    android:layout_width="250dp"
    android:layout_height="250dp"
    android:layout_below="@id/tv_song_singer"
    android:layout_centerHorizontal="true"
    android:layout_marginTop="32dp"
    android:src="@mipmap/id3_artwork" />  //圆球图片
 
<TextView
    android:id="@+id/tv_lyric_previous"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:layout_below="@id/iv_disk"
    android:layout_marginTop="16dp"
    android:gravity="center_horizontal"
    android:text="---"
    android:textAlignment="center" />  //这是为了方便“此音乐为纯音乐,请欣赏”这里的排版大小来加的,可以删除掉
 
<TextView
    android:id="@+id/tv_lyric_current"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:layout_below="@id/tv_lyric_previous"
    android:layout_marginTop="16dp"
    android:gravity="center_horizontal"
    android:text="此音乐为纯音乐,请欣赏"
    android:textAlignment="center"
    android:textSize="20dp" />  //“此音乐为纯音乐,请欣赏”这里是用来放歌词的
 
<TextView
    android:id="@+id/tv_lyric_next"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:layout_below="@id/tv_lyric_current"
    android:layout_marginTop="16dp"
    android:gravity="center_horizontal"
    android:text="---"
    android:textAlignment="center" />  //这是为了方便“此音乐为纯音乐,请欣赏”这里的排版大小来加的,可以删除掉

第二部分是用来显示音乐播放进度的SeekBar

<RelativeLayout
    android:id="@+id/rl_progress"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:layout_below="@id/tv_lyric_next"
    android:layout_marginTop="32dp">
 
    <androidx.appcompat.widget.AppCompatSeekBar  //这里一般看版本的,有点版本直接seekBar就行了,我的版本较低
        android:id="@+id/sb_progress"
        android:layout_width="match_parent"
        android:layout_height="wrap_content" />
 
    <TextView
        android:id="@+id/tv_progress_current"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_below="@id/sb_progress"
        android:layout_alignParentStart="true"
        android:layout_alignParentLeft="true"
        android:text="0:00" />  //这是两个定点,这个定点表示声音起始点
 
    <TextView
        android:id="@+id/tv_progress_total"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_below="@id/sb_progress"
        android:layout_alignParentEnd="true"
        android:layout_alignParentRight="true"
        android:text="0:00" />  //这是两个定点,这个定点表示声音终点
</RelativeLayout>

第三部分是音乐的暂停、开始、继续、前一首和后一首的选择。

这一部分可能就是排版比较烦,耐心点还是可以弄好的,调参可能费点时间。

<RelativeLayout
    android:id="@+id/rl_control"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:layout_alignParentBottom="true"
    android:layout_marginBottom="32dp">
 
    <ImageButton
        android:id="@+id/btn_prev"
        android:layout_width="64dp"
        android:layout_height="64dp"
        android:layout_centerHorizontal="true"
        android:layout_toStartOf="@id/btn_play_pause"
        android:layout_toLeftOf="@id/btn_play_pause"
        android:scaleType="fitCenter"
        android:src="@mipmap/id3_icon_prev_d" />
 
    <ImageButton
        android:id="@+id/btn_play_pause"
        android:layout_width="64dp"
        android:layout_height="64dp"
        android:layout_centerHorizontal="true"
        android:scaleType="fitCenter"
        android:src="@mipmap/id3_button_pause_n" />
 
    <ImageButton
        android:id="@+id/btn_next"
        android:layout_width="64dp"
        android:layout_height="64dp"
        android:layout_centerHorizontal="true"
        android:layout_toEndOf="@id/btn_play_pause"
        android:layout_toRightOf="@id/btn_play_pause"
        android:scaleType="fitCenter"
        android:src="@mipmap/id3_icon_next_d" />
 
</RelativeLayout>

下面一部分是MainActivity.java的编写

这一部分关键在于球型图的转动、seekbar的运行和音乐的暂停播放逻辑关系等等

import androidx.annotation.RequiresApi;
import androidx.appcompat.app.AppCompatActivity;
import androidx.interpolator.view.animation.LinearOutSlowInInterpolator;
 
import android.animation.ObjectAnimator;
import android.media.MediaPlayer;
import android.os.Build;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.animation.LinearInterpolator;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.SeekBar;
import android.widget.TextView;
 
import java.lang.reflect.Array;
import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.Timer;
import java.util.TimerTask;
 
public class MainActivity extends AppCompatActivity {
    private TextView songName, singerName;
    private ImageView diskImage;
    private TextView lyricPrev, lyricCurrent, lyricNext;
    private SeekBar musicProgress;
    private TextView currentTime, totalTime;
    private ImageButton prevBtn, playPauseBtn, nextBtn;
    private ObjectAnimator animator;
 
    private MediaPlayer player;
    private int currentPlaying = 0; //用作ArrayList下表,当前播放的歌曲、
    private ArrayList<Integer> playList = new ArrayList<>();
 
    private boolean isPausing, isPlaying;  //音乐暂停状态,音乐第一次播放之后变为true
 
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        init();
        preparePlayList();
        TimerTask timerTask = new TimerTask() {
            @Override
            public void run() {
                if (isPlaying) {
                    updateTimer();
                }
            }
        };
        new Timer().scheduleAtFixedRate(timerTask, 0, 500);
    }
 
    void init() {
        songName = findViewById(R.id.tv_song_name);
        singerName = findViewById(R.id.tv_song_singer);
        diskImage = findViewById(R.id.iv_disk);
        lyricPrev = findViewById(R.id.tv_lyric_previous);
        lyricCurrent = findViewById(R.id.tv_lyric_current);
        lyricNext = findViewById(R.id.tv_lyric_next);
        musicProgress = findViewById(R.id.sb_progress);
        currentTime = findViewById(R.id.tv_progress_current);
        totalTime = findViewById(R.id.tv_progress_total);
        prevBtn = findViewById(R.id.btn_prev);
        playPauseBtn = findViewById(R.id.btn_play_pause);
        nextBtn = findViewById(R.id.btn_next);
 
        View.OnClickListener onClick = new OnClickControl();
        prevBtn.setOnClickListener(onClick);
        playPauseBtn.setOnClickListener(onClick);
        nextBtn.setOnClickListener(onClick);
 
        OnSeekBarChangeControl onSbChange = new OnSeekBarChangeControl();
        musicProgress.setOnSeekBarChangeListener(onSbChange);
 
        animator = ObjectAnimator.ofFloat(diskImage, "rotation", 0, 360.0F);  //初始化状态
        animator.setDuration(2000);  //状态时长,10秒
        animator.setInterpolator(new LinearInterpolator());  //时间函数,有很多类型
        animator.setRepeatCount(-1); // 一直旋转
 
    }
 
    private void preparePlayList() {
        Field[] field = R.raw.class.getFields();
        for (int count = 0; count < field.length; count++) {
            Log.i("Raw Asset", field[count].getName());
            try {
                int resId = field[count].getInt(field[count]);
                playList.add(resId);
            } catch (IllegalAccessException e) {
                e.printStackTrace();
            }
        }
    }
 
    private void prepareMedia() {
        if (isPlaying) {
            player.stop();
            player.reset();
        }
        player = MediaPlayer.create(getApplicationContext(), playList.get(currentPlaying));
        int musicDuration = player.getDuration();
        musicProgress.setMax(musicDuration);
        int sec = musicDuration / 1000;
        int min = sec / 60;
        sec -= min * 60;
        String musicTime = String.format("%02d:%02d", min, sec);
        totalTime.setText(musicTime);
        player.start();
    }
 
    private void updateTimer() {
        runOnUiThread(() -> {
            int currentMs = player.getCurrentPosition();
            int sec = currentMs / 1000;
            int min = sec / 60;
            sec -= min * 60;
            String time = String.format("%02d:%02d", min, sec);
            musicProgress.setProgress(currentMs);
            currentTime.setText(time);
        });
    }
 
//这一部分很重要,对于初学者来说,一定要搞清楚这三个按钮之间的逻辑关系,因为要判断如果音乐暂停了,是执行哪个线程,跳到哪个图标上去。怎么样继续运行接下来的音乐,我这里加了日志文件,可以判断一下哪一步出错了。
    private class OnClickControl implements View.OnClickListener {  
        @RequiresApi(api = Build.VERSION_CODES.KITKAT)
        @Override
        public void onClick(View v) {
            switch (v.getId()) {
                case R.id.btn_prev:
                    //重播
                    Log.i("INFO", "onClick:重播按钮被点击!");
                    playPauseBtn.setImageResource(R.mipmap.id3_button_pause_n);  //切换成暂停键
                    animator.start();
                    if (!player.isPlaying()) {
                        currentPlaying = --currentPlaying % playList.size();
                    }
                    prepareMedia();
                    isPausing = false;
                    isPlaying = true;
                    break;
                case R.id.btn_play_pause:
                    //开始暂停
                    Log.i("INFO", "onClick:开始暂停按钮被点击!");
                    if (!isPausing && !isPlaying) { //暂停状态,且从未被播放
                        //开始播放
                        playPauseBtn.setImageResource(R.mipmap.id3_button_pause_n);  //切换成暂停键
                        animator.start();
                        prepareMedia();
                        isPlaying = true;
                    } else if (!isPausing && isPlaying) { //暂停状态,且被播放过一次
                        //继续播放
                        playPauseBtn.setImageResource(R.mipmap.id3_button_pause_n);//切换成暂停键
                        animator.resume();
                        player.start();
                    } else { //播放状态
                        //暂停播放
                        playPauseBtn.setImageResource(R.mipmap.id3_button_play_p);//切换成播放键
                        animator.pause();
                        player.pause();
                    }
                    isPausing = !isPausing;  //切换歌曲
                    break;
                case R.id.btn_next:
                    Log.i("INFO", "onClick:重播按钮被点击!");
                    //切歌
                    playPauseBtn.setImageResource(R.mipmap.id3_button_pause_n); // 切换成暂停键
                    currentPlaying = ++currentPlaying % playList.size();
                    prepareMedia();
                    animator.start();
                    isPausing = false;
                    isPlaying = true;
                    break;
                default:
                    Log.i("INFO", "onClick:按钮被点击了,但是有BUG");
                    //有BUG了
            }
        }
    }
 
    private class OnSeekBarChangeControl implements SeekBar.OnSeekBarChangeListener {
        @Override
        public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
            if (fromUser) {
                player.seekTo(progress);
            }
        }
 
        @RequiresApi(api = Build.VERSION_CODES.KITKAT)
        @Override
        public void onStartTrackingTouch(SeekBar seekBar) {
            player.pause();
            animator.pause();
        }
 
        @RequiresApi(api = Build.VERSION_CODES.KITKAT)
        @Override
        public void onStopTrackingTouch(SeekBar seekBar) {
            player.start();
            if (seekBar.getProgress() < 10) {
                animator.start();
            } else {
                animator.resume();
            }
        }
    }
}

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持我们。

(0)

相关推荐

  • android实现音乐播放器进度条效果

    本文实例为大家分享了android实现音乐播放器进度条效果的具体代码,供大家参考,具体内容如下 效果图 依赖3个对象 MediaPlayer:实现音乐播放,暂停,缓冲. SeekBar:滑动的进度条. java.util.Timer:定时器,时时更新进度条. main.xml样式文件 <TextView android:layout_width="fill_parent" android:layout_height="wrap_content" android

  • Android简易音乐播放器实现代码

    本文实例为大家分享了Android音乐播放器的具体代码,供大家参考,具体内容如下 1.播放项目内的音乐 package com.thm.g150820_android26_playmusic; import Android.media.MediaPlayer; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.view.View; import android.wid

  • Android 音乐播放器的开发实例详解

    本文将引导大家做一个音乐播放器,在做这个Android开发实例的过程中,能够帮助大家进一步熟悉和掌握学过的ListView和其他一些组件.为了有更好的学习效果,其中很多功能我们手动实现,例如音乐播放的快进快退等. 先欣赏下本实例完成后运行的界面效果: 首先我们建立项目,我使用的SDK是Android2.2的,然后在XML中进行布局. 上方是一个ListView用来显示我们的音乐列表,中间是一个SeekBar可以拖动当前音乐的播放进度,之所以用SeekBar而不用ProgressBar是因为我们需

  • 教你轻松制作Android音乐播放器

    欣赏一下我们清爽的界面吧~ 如果是只用activity来制作这样的东西简直是太小儿科了,此处我们当然用的是service 首先我们先上service的代码: 1.如果我们要访问service的属性和方法,那么在activity肯定是以bindservice的方法实现的,而在service中的onbind方法也是必须要实现的,onbind返回的Ibinder对象在activity的serviceconnection中得到使用. 2.activity获取到Ibinder对象,可以进一步获取服务对象和

  • Android实现简单音乐播放器(MediaPlayer)

    Android实现简单音乐播放器(MediaPlayer),供大家参考,具体内容如下 开发工具:Andorid Studio 1.3 运行环境:Android 4.4 KitKat 工程内容 实现一个简单的音乐播放器,要求功能有: 播放.暂停功能: 进度条显示播放进度功能 拖动进度条改变进度功能: 后台播放功能: 停止功能: 退出功能: 代码实现 导入歌曲到手机SD卡的Music目录中,这里我导入了4首歌曲:仙剑六里面的<誓言成晖>.<剑客不能说>.<镜中人>和<

  • Android音乐播放器制作 扫描本地音乐显示在手机(一)

    思路 首先是扫描本地所有的音频文件,然后全部装进集合当中,接下来就是用ListView展示在屏幕上,大概就是这几个步骤了,接下来细讲 创建一个容器 进行过数据解析的朋友都应该知道JavaBean吧,用来装载解析出来的数据,我们这里同样也要创建一个JavaBean,用来装载扫描到的音频文件,具体的代码是: package com.duanlian.mymusicplayerdemo.bean; /** * Created by user on 2016/6/24. * 放置音乐 */ public

  • Android MediaPlayer实现音乐播放器实例代码

    Android MediaPlayer实现音乐播放器 1.布局文件 <?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="fill_parent" android:layout_height=&qu

  • Android编程开发音乐播放器实例

    本文实例讲述了Android编程开发音乐播放器,分享给大家供大家参考,具体如下: 音乐播放器中综合了以下内容: SeekBar.ListView.广播接收者(以代码的形式注册Receiver).系统服务.MediaPlayer 实现的功能: 1.暂停/播放.下一首/上一首,点击某一首时播放 2.支持拖动进度条快进 3.列表排序 4.来电话时,停止播放,挂断后继续播放 5.可在后台播放 效果图: 界面: main.xml: <?xml version="1.0" encoding=

  • android暂停或停止其他音乐播放器的播放实现代码

    代码如下: 复制代码 代码如下: public static final String PLAYSTATE_CHANGED = "com.android.music.playstatechanged";    public static final String META_CHANGED = "com.android.music.metachanged";    public static final String QUEUE_CHANGED = "com

  • 简单实现Android本地音乐播放器

    音乐播放需要调用service,在此,只是简单梳理播放流程. public class PlayMusicService extends Service { //绑定服务 调用服务的方法. @Override public IBinder onBind(Intent intent) { return null; } } <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:to

随机推荐