播放音乐实现歌词刷新,参考他人代码后略做修改

干什么不好,学打代码。。。

final Handler handler = new Handler();
//开一个子线程。

    new Thread(new Runnable() {
        @Override
        public void run() {
            while (myPlayer.isPlaying()) {
                handler.post(new Runnable() {
                    @Override
                    public void run() {
                        int position = 0;
                        int currentPosition = myPlayer.getCurrentPosition();   //获取歌曲已经播放的时间
                        
                         //根据时间获得歌词的位置position
                        for (int i = 0; i < timeList.size()-1; i++) {
                            if (currentPosition < timeList.get(0)) {
                                position = 0;
                                break;
                            } else if (currentPosition >= timeList.get(i)
                                    && currentPosition < timeList.get(i + 1)) {
                                position = i;
                                break;
                            }else if(currentPosition > timeList.get(timeList.size()-1)){
                                position = timeList.size()-1;
                            }
                        }
                        
                        int i = position;                     
                        
                        //刷新3个显示歌词的TextView
                        if(i == 0) {
                            textView1.setText(" ");
                        }else if(i > 0){
                            textView1.setText( words.get( i - 1 ) );
                        }
                        textView2.setText(words.get(i));
                        if(i < words.size() - 1) {
                            textView3.setText( words.get( i + 1 ) );
                        }else if(i == words.size() - 1){
                            textView3.setText( " " );
                        }
                    }
                });

                try {
                    Thread.sleep(100);           //100ms刷新一次

                } catch (InterruptedException e) {
                }

            }
        }
    } ).start();
发布了3 篇原创文章 · 获赞 4 · 访问量 1266

猜你喜欢

转载自blog.csdn.net/qq_41014115/article/details/89304985
今日推荐