Android开源音乐播放器之自动滚动歌词

系列文章

前言

上一节我们仿照云音乐实现了黑胶唱片专辑封面,这节我们该实现歌词显示了。当然,歌词不仅仅是显示就完了,作为一个有素质的音乐播放器,我们当然还需要根据歌曲进度自动滚动歌词,并且要支持上下拖动。

简介

Android歌词控件,支持上下拖动歌词,歌词自动换行,自定义属性。

更新说明

v 2.0

  • 新增上下拖动歌词功能

v 1.4

  • 解析歌词放在工作线程中
  • 优化多行歌词时动画不流畅

v 1.3

  • 支持多个时间标签

v 1.2

  • 支持RTL(从右向左)语言

v 1.1

  • 新增歌词自动换行
  • 新增自定义歌词Padding
  • 优化歌词解析

v 1.0

  • 支持自动滚动
  • 支持自定义属性

使用

Gradle

// "latestVersion"改为文首徽章后对应的数值
compile 'me.wcy:lrcview:latestVersion'

属性

属性 描述
lrcTextSize 歌词文本字体大小
lrcNormalTextColor 非当前行歌词字体颜色
lrcCurrentTextColor 当前行歌词字体颜色
lrcTimelineTextColor 拖动歌词时选中歌词的字体颜色
lrcDividerHeight 歌词间距
lrcAnimationDuration 歌词滚动动画时长
lrcLabel 没有歌词时屏幕中央显示的文字,如“暂无歌词”
lrcPadding 歌词文字的左右边距
lrcTimelineColor 拖动歌词时时间线的颜色
lrcTimelineHeight 拖动歌词时时间线的高度
lrcPlayDrawable 拖动歌词时左侧播放按钮图片
lrcTimeTextColor 拖动歌词时右侧时间字体颜色
lrcTimeTextSize 拖动歌词时右侧时间字体大小

方法

方法 描述
loadLrc(File) 加载歌词文件
loadLrc(String) 加载歌词文本
hasLrc() 歌词是否有效
setLabel(String) 设置歌词为空时视图中央显示的文字,如“暂无歌词”
updateTime(long) 刷新歌词
onDrag(long) 将歌词滚动到指定时间,已弃用,请使用 updateTime(long) 代替
setOnPlayClickListener(OnPlayClickListener) 设置拖动歌词时,播放按钮点击监听器。如果为非 null ,则激活歌词拖动功能,否则将将禁用歌词拖动功能
setNormalColor(int) 设置非当前行歌词字体颜色
setCurrentColor(int) 设置当前行歌词字体颜色
setTimelineTextColor 设置拖动歌词时选中歌词的字体颜色
setTimelineColor 设置拖动歌词时时间线的颜色
setTimeTextColor 设置拖动歌词时右侧时间字体颜色

思路分析

正常播放时,当前播放的那一行应该在视图中央,首先计算出每一行位于中央时画布应该滚动的距离。

将所有歌词按顺序画出,然后将画布滚动的相应的距离,将正在播放的歌词置于屏幕中央。

歌词滚动时要有动画,使用属性动画即可,我们可以使用当前行和上一行的滚动距离作为动画的起止值。

多行歌词绘制采用StaticLayout。

上下拖动时,歌词跟随手指滚动,绘制时间线。

手指离开屏幕时,一段时间内,如果没有下一步操作,则隐藏时间线,同时将歌词滚动到实际位置,回到正常播放状态;

如果点击播放按钮,则跳转到指定位置,回到正常播放状态。

代码实现

onDraw 中将歌词文本绘出,mOffset 是当前应该滚动的距离

@Override
protected void onDraw(Canvas canvas) {
    super.onDraw(canvas);

    int centerY = getHeight() / 2;

    // 无歌词文件
    if (!hasLrc()) {
        mLrcPaint.setColor(mCurrentTextColor);
        @SuppressLint("DrawAllocation")
        StaticLayout staticLayout = new StaticLayout(mDefaultLabel, mLrcPaint, (int) getLrcWidth(),
                Layout.Alignment.ALIGN_CENTER, 1f, 0f, false);
        drawText(canvas, staticLayout, centerY);
        return;
    }

    int centerLine = getCenterLine();

    if (isShowTimeline) {
        mPlayDrawable.draw(canvas);

        mTimePaint.setColor(mTimelineColor);
        canvas.drawLine(mTimeTextWidth, centerY, getWidth() - mTimeTextWidth, centerY, mTimePaint);

        mTimePaint.setColor(mTimeTextColor);
        String timeText = LrcUtils.formatTime(mLrcEntryList.get(centerLine).getTime());
        float timeX = getWidth() - mTimeTextWidth / 2;
        float timeY = centerY - (mTimeFontMetrics.descent + mTimeFontMetrics.ascent) / 2;
        canvas.drawText(timeText, timeX, timeY, mTimePaint);
    }

    canvas.translate(0, mOffset);

    float y = 0;
    for (int i = 0; i < mLrcEntryList.size(); i++) {
        if (i > 0) {
            y += (mLrcEntryList.get(i - 1).getHeight() + mLrcEntryList.get(i).getHeight()) / 2 + mDividerHeight;
        }
        if (i == mCurrentLine) {
            mLrcPaint.setColor(mCurrentTextColor);
        } else if (isShowTimeline && i == centerLine) {
            mLrcPaint.setColor(mTimelineTextColor);
        } else {
            mLrcPaint.setColor(mNormalTextColor);
        }
        drawText(canvas, mLrcEntryList.get(i).getStaticLayout(), y);
    }
}

手势监听器

private GestureDetector.SimpleOnGestureListener mSimpleOnGestureListener = new GestureDetector.SimpleOnGestureListener() {
    @Override
    public boolean onDown(MotionEvent e) {
        if (hasLrc() && mOnPlayClickListener != null) {
            mScroller.forceFinished(true);
            removeCallbacks(hideTimelineRunnable);
            isTouching = true;
            isShowTimeline = true;
            invalidate();
            return true;
        }
        return super.onDown(e);
    }

    @Override
    public boolean onScroll(MotionEvent e1, MotionEvent e2, float distanceX, float distanceY) {
        if (hasLrc()) {
            mOffset += -distanceY;
            mOffset = Math.min(mOffset, getOffset(0));
            mOffset = Math.max(mOffset, getOffset(mLrcEntryList.size() - 1));
            invalidate();
            return true;
        }
        return super.onScroll(e1, e2, distanceX, distanceY);
    }

    @Override
    public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY) {
        if (hasLrc()) {
            mScroller.fling(0, (int) mOffset, 0, (int) velocityY, 0, 0, (int) getOffset(mLrcEntryList.size() - 1), (int) getOffset(0));
            isFling = true;
            return true;
        }
        return super.onFling(e1, e2, velocityX, velocityY);
    }

    @Override
    public boolean onSingleTapConfirmed(MotionEvent e) {
        if (hasLrc() && isShowTimeline && mPlayDrawable.getBounds().contains((int) e.getX(), (int) e.getY())) {
            int centerLine = getCenterLine();
            long centerLineTime = mLrcEntryList.get(centerLine).getTime();
            // onPlayClick 消费了才更新 UI
            if (mOnPlayClickListener != null && mOnPlayClickListener.onPlayClick(centerLineTime)) {
                isShowTimeline = false;
                removeCallbacks(hideTimelineRunnable);
                mCurrentLine = centerLine;
                invalidate();
                return true;
            }
        }
        return super.onSingleTapConfirmed(e);
    }
};

滚动动画

private void scrollTo(int line, long duration) {
    float offset = getOffset(line);
    endAnimation();

    mAnimator = ValueAnimator.ofFloat(mOffset, offset);
    mAnimator.setDuration(duration);
    mAnimator.setInterpolator(new LinearInterpolator());
    mAnimator.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {
        @Override
        public void onAnimationUpdate(ValueAnimator animation) {
            mOffset = (float) animation.getAnimatedValue();
            invalidate();
        }
    });
    mAnimator.start();
}

代码比较简单,大家根据源码和注释很容易就能看懂。到这里,我们已经实现了可拖动的歌词控件了。

截图看比较简单,大家可以运行源码或下载波尼音乐查看详细效果。

关于作者

简书:http://www.jianshu.com/users/3231579893ac

微博:http://weibo.com/wangchenyan1993

License

Copyright 2017 wangchenyan

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

   http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • Android 自定义View的各种姿势1 Activity的显示之ViewRootImpl详解 Activity...
    passiontim阅读 172,862评论 25 708
  • 发现 关注 消息 iOS 第三方库、插件、知名博客总结 作者大灰狼的小绵羊哥哥关注 2017.06.26 09:4...
    肇东周阅读 12,192评论 4 61
  • 2017-01-11 鉴于我的掉以轻心和胆大恣意,一不小心就摔骨折了,我想说流年不利,但是老爸纠正我说是自己不小心...
    2000到2003阅读 1,563评论 3 1
  • 读者: 老师,你好。我想咨询一个问题,这个问题我不知道值不值得问,还是它只是个小问题。我觉得可能不是我一个人这样,...
    观心阁笔记阅读 1,014评论 0 1
  • 看一路电影 剧情每每被我们猜透 下一个路口 谁与谁相逢 又与谁错过 演员的无奈 导演主导着全片 人生而逢时 才遇到...
    专属9877阅读 204评论 0 1