转载请注明出处:
http://blog.csdn.net/iwanghang/article/details/51388896
觉得博文有用,请点赞,请留言,请关注,谢谢!~
实现功能:
已存在歌曲歌词下载
后续将博文,将实现已下载音乐扫描功能。
因为,没有自己的服务器,所以网络音乐所有相关功能(包含搜索音乐、下载音乐、下载歌词)均无法保证时效性,建议,尽快下载和练习;如果你下载时候,已经因为我采集的服务器更改规则,请给我留言,如果可以解决,我将在有空的时候献上新的源码。
截止到目前的源码下载:
http://download.csdn.net/album/detail/3105
欢迎移动开发爱好者交流:我的微信是iwanghang
另外,我打算开始找工作,如果沈阳或周边城市公司有意,也请与我联系。
转载请注明出处: http://blog.csdn.net/iwanghang/article/details/51388896
觉得博文有用,请点赞,请留言,请关注,谢谢!~
觉得博文有用,请点赞,请留言,请关注,谢谢!~
实现功能:
已存在歌曲歌词下载
后续将博文,将实现已下载音乐扫描功能。
因为,没有自己的服务器,所以网络音乐所有相关功能(包含搜索音乐、下载音乐、下载歌词)均无法保证时效性,建议,尽快下载和练习;如果你下载时候,已经因为我采集的服务器更改规则,请给我留言,如果可以解决,我将在有空的时候献上新的源码。
截止到目前的源码下载:
http://download.csdn.net/album/detail/3105
(最新的,请下载最后一个,本博文对应版本2.2
;如果需要逐步实现的过程,请下载所有)
欢迎移动开发爱好者交流:我的微信是iwanghang
另外,我打算开始找工作,如果沈阳或周边城市公司有意,也请与我联系。
实现效果如图:
实现代码如下:
PlayActivity如下:
package com.iwanghang.drmplayer;import android.graphics.Bitmap;
import android.media.MediaPlayer;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.support.v4.view.ViewPager;
import android.support.v4.view.ViewPager.OnPageChangeListener;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.ImageView;
import android.widget.SeekBar;
import android.widget.SeekBar.OnSeekBarChangeListener;
import android.widget.TextView;
import android.widget.Toast;import com.douzi.android.view.DefaultLrcBuilder;
import com.douzi.android.view.ILrcBuilder;
import com.douzi.android.view.ILrcView;
import com.douzi.android.view.LrcRow;
import com.douzi.android.view.LrcView;
import com.iwanghang.drmplayer.adapter.ViewPagerAdapter;
import com.iwanghang.drmplayer.utils.Constant;
import com.iwanghang.drmplayer.utils.DownloadUtils;
import com.iwanghang.drmplayer.utils.ImageUtils;
import com.iwanghang.drmplayer.utils.MediaUtils;
import com.iwanghang.drmplayer.utils.SearchMusicUtils;
import com.iwanghang.drmplayer.vo.Mp3Info;
import com.lidroid.xutils.db.sqlite.Selector;
import com.lidroid.xutils.exception.DbException;import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStreamReader;
import java.lang.ref.WeakReference;
import java.util.ArrayList;
import java.util.List;import static com.iwanghang.drmplayer.PlayService.ORDER_PLAY;
import static com.iwanghang.drmplayer.PlayService.RANDOM_PLAY;
import static com.iwanghang.drmplayer.PlayService.SINGLE_PLAY;/*** PlayActivity 点击MyMusicListFragment(本地音乐)底部UI中的专辑封面图片打开的Activity*/
public class PlayActivity extends BaseActivity implements OnClickListener, OnSeekBarChangeListener ,OnPageChangeListener {private TextView textView2_title;//歌名private ImageView imageView1_ablum;//专辑封面图片private SeekBar seekBar1;//进度条private TextView textView1_start_time, textView1_end_time;//开始时间,结束时间private ImageView imageView1_play_mode;//菜单private ImageView imageView3_previous, imageView2_play_pause, imageView1_next;//上一首,播放暂停,下一首private ImageView imageView1_ablum_reflection;//专辑封面图片倒影private ImageView imageView1_favorite;//收藏按钮//private ArrayList<Mp3Info> mp3Infos;//private int position;//当前播放的位置private boolean isPause = false;//当前播放的是否为暂停状态private static final int UPDATE_TIME = 0x10;//更新播放事件的标记private DRMPlayerApp app;//取出全局对象 方便调用//歌词private ViewPager viewPager;private LrcView lrcView;// 自定义歌词视图private ArrayList<View> views = new ArrayList<>();private static final int UPDATE_LRC = 0x20;//更新播放事件的标记ILrcView mLrcView;public final static String TAG = "PlayActivity";private MediaPlayer mPlayer;private ViewPagerAdapter adapter;@Overrideprotected void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);setContentView(R.layout.activity_music_play);//取出全局对象 方便调用app = (DRMPlayerApp) getApplication();//初始化界面信息//textView2_title = (TextView) findViewById(R.id.textView2_title);//歌名//imageView1_ablum = (ImageView) findViewById(R.id.imageView1_ablum);//专辑封面图片seekBar1 = (SeekBar) findViewById(R.id.seekBar1);//进度条textView1_start_time = (TextView) findViewById(R.id.textView1_start_time);//开始时间textView1_end_time = (TextView) findViewById(R.id.textView1_end_time);//结束时间imageView1_play_mode = (ImageView) findViewById(R.id.imageView1_play_mode);//菜单imageView3_previous = (ImageView) findViewById(R.id.imageView3_previous);//上一首imageView2_play_pause = (ImageView) findViewById(R.id.imageView2_play_pause);//播放暂停imageView1_next = (ImageView) findViewById(R.id.imageView1_next);//下一首imageView1_favorite = (ImageView) findViewById(R.id.imageView1_favorite);//收藏按钮lrcView = (LrcView) findViewById(R.id.lrcView);//自定义歌词视图//注册按钮点击监听事件imageView1_play_mode.setOnClickListener(this);imageView2_play_pause.setOnClickListener(this);imageView3_previous.setOnClickListener(this);imageView1_next.setOnClickListener(this);seekBar1.setOnSeekBarChangeListener(this);imageView1_favorite.setOnClickListener(this);//mp3Infos = MediaUtils.getMp3Infos(this);//bindPlayService();//绑定服务,异步过程,绑定后需要取得相应的值,来更新界面myHandler = new MyHandler(this);//独立音乐播放界面 和 歌词界面//viewPager = (ViewPager) findViewById(R.id.fgv_player_main);viewPager = (ViewPager) findViewById(R.id.viewpager);initViewPager();//初始化//以下直接调用change()是不行的,因为异步问题,会发生NullPointerException空指针异常//从MyMusicListFragment的专辑封面图片点击时间传过来的position(当前播放的位置)//position = getIntent().getIntExtra("position",0);//change(position);//通过在BaseActivity中绑定Service,添加如下代码实现change()//musicUpdatrListener.onChange(playService.getCurrentProgeress());//从MyMusicListFragment的专辑封面图片点击时间传过来的isPause(当前播放的是否为暂停状态)//isPause = getIntent().getBooleanExtra("isPause",false);// mLrcView = new LrcView(this, null);// setContentView((View) mLrcView);//// //在目标位置读取lrc文件// File LrcDirFile = new File(Environment.getExternalStorageDirectory() + Constant.DIR_LRC);// System.out.println("LrcDirFile : " + LrcDirFile);// if (!LrcDirFile.exists()) {// LrcDirFile.mkdirs();// }// //把lrc转成字符串// String lrc = LrcDirFile + "/" + "山丘" + ".lrc";// //Log.d的输出颜色是蓝色的,仅输出debug调试的意思,但他会输出上层的信息,过滤起来可以通过DDMS的Logcat标签来选择.// Log.d(TAG, "lrc:" + lrc);//// //把lrc的字符串 转成数组// ILrcBuilder builder = new DefaultLrcBuilder();// List<LrcRow> rows = builder.getLrcRows(lrc);//// //把lrc数组 设置到mLrcView里// mLrcView.setLrc(rows);// //beginLrcPlay();//// //设置监听器,监听歌词滚动// mLrcView.setListener(new ILrcView.LrcViewListener() {// public void onLrcSeeked(int newPosition, LrcRow row) {// if (mPlayer != null) {// Log.d(TAG, "onLrcSeeked:" + row.time);// mPlayer.seekTo((int)row.time);//用户滑动歌词界面,调整进度// }// }// });}private void initViewPager() {//专辑封面图片Pager与歌词Pager//View album_image_layout = getLayoutInflater().inflate(R.layout.album_image_layout, null);//System.out.println("PlayActivity.initViewPager.album_image_layout:" + album_image_layout);View album_image_layout = LayoutInflater.from(getApplicationContext()).inflate(R.layout.album_image_layout, null);System.out.println("PlayActivity.initViewPager.album_image_layout:" + album_image_layout);//初始化界面信息//textView2_title = (TextView) findViewById(R.id.textView2_title);//歌名//这里要注意下,直接findViewById,返回的是textView2_title是null;像下面这样,加上layout才可以,否则在change的时候会报空指针异常textView2_title = (TextView) album_image_layout.findViewById(R.id.textView2_title);//歌名//System.out.println("PlayActivity.initViewPager.textView2_title:" + textView2_title);//System.out.println("PlayActivity.initViewPager.textView2_title.getText:" + textView2_title.getText());imageView1_ablum = (ImageView) album_image_layout.findViewById(R.id.imageView1_ablum);//专辑封面图片imageView1_ablum_reflection = (ImageView) album_image_layout.findViewById(R.id.imageView1_ablum_reflection);//专辑封面图片倒影views.add(album_image_layout);//添加专辑封面图片Pager//View lrc_layout = getLayoutInflater().inflate(R.layout.lrc_layout, null);View lrc_layout = LayoutInflater.from(getApplicationContext()).inflate(R.layout.lrc_layout, null);System.out.println("PlayActivity.initViewPager.lrc_layout:" + lrc_layout);lrcView = (LrcView) lrc_layout.findViewById(R.id.lrcView);//设置滚动事件lrcView.setListener(new ILrcView.LrcViewListener() {@Overridepublic void onLrcSeeked(int newPosition, LrcRow row) {if (playService.isPlaying()) {playService.seekTo((int) row.time);}}});lrcView.setLoadingTipText("正在加载歌词......");lrcView.setBackgroundResource(R.mipmap.app_splash_bg);lrcView.getBackground().setAlpha(150);//背景透明度0-255views.add(lrc_layout);System.out.println("PlayActivity.initViewPager.views:" + views);//adapter = new ViewPagerAdapter(views);adapter = new ViewPagerAdapter(views);viewPager.setAdapter(adapter);//viewPager.setAdapter(new ViewPagerAdapter(views));System.out.println("PlayActivity.initViewPager.viewPager:" + viewPager);viewPager.addOnPageChangeListener(this);System.out.println("PlayActivity.initViewPager.viewPager:" + viewPager);}//把播放服务的绑定和解绑放在onResume,onPause里,好处是,每次回到当前Activity就获取一次播放状态@Overrideprotected void onResume() {super.onResume();bindPlayService();//绑定服务}@Overrideprotected void onPause() {super.onPause();unbindPlayService();//解绑服务}@Overrideprotected void onDestroy() {super.onDestroy();unbindPlayService();//解绑服务}//Handler用于更新已经播放时间private static MyHandler myHandler;//进度条改变 (fromUser 是否来自用户的改变 , 而不是程序自身控制的改变)@Overridepublic void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {if (fromUser) {//playService.pause();//暂停playService.seekTo(progress);//寻找指定的时间位置 (跳到某个时间点进行播放)//playService.start();//播放}}//进度条开始触摸@Overridepublic void onStartTrackingTouch(SeekBar seekBar) {}//进度条停止触摸@Overridepublic void onStopTrackingTouch(SeekBar seekBar) {}//页面滚动@Overridepublic void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {}//页面选择@Overridepublic void onPageSelected(int position) {}//页面滚动状态改变@Overridepublic void onPageScrollStateChanged(int state) {}static class MyHandler extends Handler {private PlayActivity playActivity;private WeakReference<PlayActivity> weak;//弱引用public MyHandler(PlayActivity playActivity) {//this.playActivity = playActivity;weak = new WeakReference<PlayActivity>(playActivity);}@Overridepublic void handleMessage(Message msg) {super.handleMessage(msg);//System.out.println("PlayActivity.MyHandler.weak = " + weak);playActivity = weak.get();//System.out.println("PlayActivity.MyHandler.playActivity = " + playActivity);if (playActivity != null) {switch (msg.what) {case UPDATE_TIME://更新时间(已经播放时间)playActivity.textView1_start_time.setText(MediaUtils.formatTime((int) msg.obj));break;case UPDATE_LRC:playActivity.lrcView.seekLrcToTime((int) msg.obj);break;default:break;}}}}@Overridepublic void publish(int progress) {//以下是是直接调用线程,但是不能这样做,会报错,线程异常//textView1_start_time.setText(MediaUtils.formatTime(progress));//所以,我们需要使用Handler//Message msg = myHandler.obtainMessage(UPDATE_TIME);//用于更新已经播放时间//msg.arg1 = progress;//用于更新已经播放时间//myHandler.sendMessage(msg);//用于更新已经播放时间//seekBar1.setProgress(progress);myHandler.obtainMessage(UPDATE_TIME, progress).sendToTarget();seekBar1.setProgress(progress);myHandler.obtainMessage(UPDATE_LRC, progress).sendToTarget();//System.out.println("PlayActivity.publish.myHandler = " + myHandler);//System.out.println("PlayActivity.publish.UPDATE_LRC = " + UPDATE_LRC);//System.out.println("PlayActivity.publish.progress = " + progress);}@Overridepublic void change(int position) {//初始化,独立播放界面的歌曲切换后的初始化界面上的歌曲信息//if (this.playService.isPlaying()) {//获取是否为播放状态//System.out.println("PlayActivity.change.position = " + position);Mp3Info mp3Info = playService.mp3Infos.get(position);//System.out.println("PlayActivity.change.getTitle = " + mp3Info.getTitle());textView2_title.setText(mp3Info.getTitle());//设置歌名//textView2_title.setTtileText(mp3Info.getTitle());//设置歌名//System.out.println("PlayActivity.change.textView2_title = " + textView2_title);//System.out.println("PlayActivity.change.getText : " + textView2_title.getText());//System.out.println("PlayActivity.change.getText : " + textView2_title.getTtileText());//下面这句话是提交更新UI的,但是这个功能在adapter里面实现了,但是实现的方式,只适合UI需要更新的内容很少的时候//而且,就算使用,也是设置了专辑图片和倒影,以后使用,不是这里.//之所以放在这里,是因为我开始调试的时候,无法setText,最后通过Debug找到了问题所在//以后我会专门开个博文,介绍一下Debug//adapter.notifyDataSetChanged();//setText后,歌名没有显示,但是可以getText,尝试隐藏/显示,来刷新UI,结果歌名还是没有显示//viewPager.setVisibility(View.GONE);//getWindow().setFeatureInt(Window.FEATURE_CUSTOM_TITLE, R.layout.activity_music_play);//viewPager.setVisibility(View.VISIBLE);//setText后,歌名没有显示,但是可以getText,尝试隐藏/显示,来刷新UI,结果歌名还是没有显示//viewPager.setVisibility(View.GONE);//viewPager.setVisibility(View.VISIBLE);//获取专辑封面图片Bitmap albumBitmap = MediaUtils.getArtwork(this, mp3Info.getId(), mp3Info.getAlbumId(), true, false);//改变播放界面专辑封面图片imageView1_ablum.setImageBitmap(albumBitmap);textView1_end_time.setText(MediaUtils.formatTime(mp3Info.getDuration()));//设置结束时间imageView2_play_pause.setImageResource(R.mipmap.app_music_pause);//设置暂停图片seekBar1.setProgress(0);//设置当前进度为0seekBar1.setMax((int) mp3Info.getDuration());//设置进度条最大值为MP3总时间if (playService.isPlaying()) {imageView2_play_pause.setImageResource(R.mipmap.app_music_pause);} else {imageView2_play_pause.setImageResource(R.mipmap.app_music_play);}if (imageView1_ablum != null) {imageView1_ablum_reflection.setImageBitmap(ImageUtils.createReflectionBitmapForSingle(albumBitmap));//显示倒影}switch (playService.getPlay_mode()) {case ORDER_PLAY://顺序播放imageView1_play_mode.setImageResource(R.mipmap.app_mode_order);//imageView2_play_pause.setTag(ORDER_PLAY);break;case PlayService.RANDOM_PLAY://随机播放imageView1_play_mode.setImageResource(R.mipmap.app_mode_random);//imageView2_play_pause.setTag(RANDOM_PLAY);break;case PlayService.SINGLE_PLAY://单曲循环imageView1_play_mode.setImageResource(R.mipmap.app_mode_single);//imageView2_play_pause.setTag(SINGLE_PLAY);break;default:break;}long id = getId(mp3Info);//初始化收藏状态try {Mp3Info loveMp3Info = app.dbUtils.findFirst(Selector.from(Mp3Info.class).where("mp3InfoId", "=", mp3Info.getMp3InfoId()));//查出歌曲,SQL语句System.out.println("初始化收藏状态" + loveMp3Info);
// if (loveMp3Info != null) {
// imageView1_favorite.setImageResource(R.mipmap.app_love_selected);
// } else {
// imageView1_favorite.setImageResource(R.mipmap.app_love_unselected);
// }if (loveMp3Info != null) {System.out.println("loveMp3Info.getIsLove() = " + loveMp3Info.getIsLove());if (loveMp3Info.getIsLove() == 0) {//返回值不为null,且,isLove为0时,也显示为'未收藏'imageView1_favorite.setImageResource(R.mipmap.app_love_unselected);}else {//返回值为null,且,isLove为1时,一定显示为'已收藏'imageView1_favorite.setImageResource(R.mipmap.app_love_selected);}} else {//返回值为null,一定显示为'未收藏'imageView1_favorite.setImageResource(R.mipmap.app_love_unselected);}} catch (DbException e) {e.printStackTrace();}//歌词String songName = mp3Info.getTitle();String artistName = mp3Info.getArtist();//歌词功能还不完善,后面会博文,会继续完善,暂时使用我已经下载好的lrc测试效果.//songName = "山丘";//测试用的lrc的歌名String lrcPath = Environment.getExternalStorageDirectory() + Constant.DIR_LRC + "/" + songName + ".lrc";File lrcFile = new File(lrcPath);if (!lrcFile.exists()){//下载歌词System.out.println("下载歌词");DownloadUtils.getsInstance().downloadLRC(songName,artistName,myHandler);Toast.makeText(PlayActivity.this, "请下次播放本首歌曲时,将显示歌词", Toast.LENGTH_SHORT).show();}else{loadLRC(lrcFile);}}//如果是本地音乐,id就是id;如果是收藏音乐,id则是mp3InfoId//提供给 收藏按钮 点击事件时 调用.private long getId(Mp3Info mp3Info){//初始收藏状态long id = 0;switch (playService.getChangePlayList()){case PlayService.MY_MUSIC_LIST:System.out.println("当前为本地列表");id = mp3Info.getId();System.out.println("id =" + id);break;case PlayService.LOVE_MUSIC_LIST:System.out.println("当前为收藏列表");id = mp3Info.getMp3InfoId();System.out.println("id =" + id);break;default:break;}return id;}//点击事件@Overridepublic void onClick(View v) {switch (v.getId()) {case R.id.imageView2_play_pause: {//播放暂停按钮if (playService.isPlaying()) {//如果是播放状态imageView2_play_pause.setImageResource(R.mipmap.app_music_play);//设置播放图片playService.pause();} else {if (playService.isPause()) {imageView2_play_pause.setImageResource(R.mipmap.app_music_pause);//设置暂停图片playService.start();//播放事件} else {//只有打开APP没有点击任何歌曲,同时,直接点击暂停播放按钮时.才会调用//playService.play(0);//只有打开APP没有点击任何歌曲,同时,直接点击暂停播放按钮时.才会调用//默认播放的是,在PlayService的onCreate中 恢复状态值playService.play(playService.getCurrentPosition());}}break;}case R.id.imageView1_next: {//下一首按钮playService.next();//下一首break;}case R.id.imageView3_previous: {//上一首按钮playService.prev();//上一首break;}case R.id.imageView1_play_mode: {//循环模式按钮//int mode = (int) imageView1_play_mode.getTag();/*** 以下Tosat内容,在strings.xml里,添加对应代码*<string name="order_play">顺序播放</string>*<string name="random_play">随机播放</string>*<string name="single_play">单曲循环</string>*/switch (playService.getPlay_mode()) {case ORDER_PLAY:imageView1_play_mode.setImageResource(R.mipmap.app_mode_random);//imageView1_play_mode.setTag(RANDOM_PLAY);playService.setPlay_mode(RANDOM_PLAY);//Toast.makeText(getApplicationContext(),"随机播放",Toast.LENGTH_SHORT).show();//这句也可以//Toast.makeText(PlayActivity.this, "随机播放", Toast.LENGTH_SHORT).show();//这句也可以Toast.makeText(PlayActivity.this, getString(R.string.random_play), Toast.LENGTH_SHORT).show();break;case RANDOM_PLAY:imageView1_play_mode.setImageResource(R.mipmap.app_mode_single);//imageView1_play_mode.setTag(SINGLE_PLAY);playService.setPlay_mode(SINGLE_PLAY);//Toast.makeText(getApplicationContext(),"单曲循环",Toast.LENGTH_SHORT).show();//这句也可以//Toast.makeText(PlayActivity.this, "单曲循环", Toast.LENGTH_SHORT).show();//这句也可以Toast.makeText(PlayActivity.this, getString(R.string.single_play), Toast.LENGTH_SHORT).show();break;case SINGLE_PLAY:imageView1_play_mode.setImageResource(R.mipmap.app_mode_order);//imageView1_play_mode.setTag(ORDER_PLAY);playService.setPlay_mode(ORDER_PLAY);//Toast.makeText(getApplicationContext(),"顺序播放",Toast.LENGTH_SHORT).show();//这句也可以//Toast.makeText(PlayActivity.this, "顺序播放", Toast.LENGTH_SHORT).show();//这句也可以Toast.makeText(PlayActivity.this, getString(R.string.order_play), Toast.LENGTH_SHORT).show();break;}break;}case R.id.imageView1_favorite: {//收藏按钮 //在vo.Mp3Info里 private long mp3InfoId;//在收藏音乐时用于保存原始IDMp3Info mp3Info = playService.mp3Infos.get(playService.getCurrentPosition());//查出歌曲System.out.println(mp3Info);try {Mp3Info loveMp3Info = app.dbUtils.findFirst(Selector.from(Mp3Info.class).where("mp3InfoId","=",getId(mp3Info)));//查出歌曲,SQL语句System.out.println(loveMp3Info);if (loveMp3Info==null){//返回值为null,则一定需要saveSystem.out.println("不在音乐收藏数据库中 保存音乐数据 原始数据: " + mp3Info);mp3Info.setMp3InfoId(mp3Info.getId());mp3Info.setIsLove(1);System.out.println(mp3Info);app.dbUtils.save(mp3Info);//在音乐收藏数据库 保存音乐System.out.println("save");imageView1_favorite.setImageResource(R.mipmap.app_love_selected);//以下是:调试使用,保存以后再查一遍loveMp3Info = app.dbUtils.findFirst(Selector.from(Mp3Info.class).where("mp3InfoId","=",getId(mp3Info)));//查出歌曲,SQL语句System.out.println("调试使用,保存以后再查一遍 最新数据: " + loveMp3Info);}else {//返回值不为null,则一定需要updateSystem.out.println("在音乐收藏数据库中 更新音乐数据 原始数据: " + loveMp3Info);int isLove = loveMp3Info.getIsLove();if (isLove==1){//返回值不为null,且,isLove为1时;设置isLove为0,同时显示为'未收藏'loveMp3Info.setIsLove(0);imageView1_favorite.setImageResource(R.mipmap.app_love_unselected);}else {//返回值不为null,且,isLove为0时;设置isLove为1,同时显示为'已收藏'loveMp3Info.setIsLove(1);imageView1_favorite.setImageResource(R.mipmap.app_love_selected);}System.out.println("update");app.dbUtils.update(loveMp3Info,"isLove");//更新loveMp3Info数据//以下是:调试使用,更新以后再查一遍loveMp3Info = app.dbUtils.findFirst(Selector.from(Mp3Info.class).where("mp3InfoId", "=", getId(mp3Info)));//查出歌曲,SQL语句System.out.println("调试使用,更新以后再查一遍 最新数据: " + loveMp3Info);}} catch (DbException e) {e.printStackTrace();}break;}default:break;}}//加载歌词private void loadLRC(File lrcFile){StringBuffer buf = new StringBuffer(1024 * 10);char[] chars = new char[1024];try {BufferedReader in = new BufferedReader(new InputStreamReader(new FileInputStream(lrcFile)));int len = -1;while ((len = in.read(chars)) != -1){buf.append(chars,0,len);}in.close();} catch (FileNotFoundException e) {e.printStackTrace();}catch (IOException e) {e.printStackTrace();}ILrcBuilder builder = new DefaultLrcBuilder();List<LrcRow> rows = builder.getLrcRows(buf.toString());lrcView.setLrc(rows);//加载专辑封面图片为背景的方法(实际使用,发现效果不理想)//long id = mp3Info.getMp3InfoId()==0?mp3Info.getId:mp3Info.getMp3InfoId();//Bitmap bg = MediaUtils.getArtwork(this, id ,mp3Info.getAlbumId(),false,false);//if(bg != null){// lrcView.getBackground(new BitmapDrawable(getResources(),bg));// lrcView.getBackground().setAlpha(120);//}}}
package com.iwanghang.drmplayer.utils;import android.os.Environment;
import android.os.Handler;
import android.os.Message;import com.iwanghang.drmplayer.vo.SearchResult;
import com.squareup.okhttp.OkHttpClient;
import com.squareup.okhttp.Request;
import com.squareup.okhttp.Response;import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.select.Elements;import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.PrintStream;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;import javax.xml.parsers.ParserConfigurationException;/*** Created by iwanghang on 16/5/3.* 网络音乐下载工具类*/
public class DownloadUtils {private static final String DOWNLOAD_URL = "/download?_o=%2Fsearch%2Fsong";private static final int SUCCESS_LRC = 1;//下载歌词成功private static final int FAILED_LRC = 2;//下载歌词失败private static final int SUCCESS_MP3 = 3;//下载歌曲成功private static final int FAILED_MP3 = 4;//下载歌曲失败private static final int GET_MP3_URL = 5;//获取音乐下载地址成功private static final int GET_FAILED_MP3_URL = 6;//获取音乐下载地址失败private static final int MUSIC_EXISTS = 7;//下载时,音乐已存在private static DownloadUtils sInstance;private OnDownloadListener mListener;private ExecutorService mThreadPool;/***设置回调监听器对象* @param mListener* @return*/public DownloadUtils setListener(OnDownloadListener mListener){this.mListener = mListener;return this;}//获取下载工具的实例public synchronized static DownloadUtils getsInstance(){if (sInstance == null){try {sInstance = new DownloadUtils();} catch (ParserConfigurationException e) {e.printStackTrace();}}return sInstance;}/*** 下载的具体业务方法* @throws ParserConfigurationException*/private DownloadUtils() throws ParserConfigurationException{mThreadPool = Executors.newSingleThreadExecutor();}public void download(final SearchResult searchResult){final Handler handler = new Handler(){@Overridepublic void handleMessage(Message msg) {switch (msg.what){case SUCCESS_LRC:if (mListener != null) mListener.onDowload(searchResult.getMusicName()+"的歌词下载成功");break;case FAILED_LRC:if (mListener != null) mListener.onFailed(searchResult.getMusicName()+"的歌词下载失败");break;case GET_MP3_URL:System.out.println("GET_MP3_URL:"+msg.obj);downloadMusic(searchResult,(String)msg.obj,this);break;case GET_FAILED_MP3_URL:if (mListener != null) mListener.onFailed(searchResult.getMusicName()+"的MP3下载失败");break;case SUCCESS_MP3:if (mListener != null) mListener.onDowload(searchResult.getMusicName()+"的MP3已经下载");String url = Constant.MIGU_URL + searchResult.getUrl();System.out.println("download lrc:"+url);downloadLRC(searchResult.getMusicName(),searchResult.getArtist(),this);break;case FAILED_MP3:if (mListener != null) mListener.onFailed(searchResult.getMusicName()+"的MP3下载失败");break;case MUSIC_EXISTS:if (mListener != null) mListener.onFailed(searchResult.getMusicName()+"已存在");break;}}};getDownloadMusicURL(searchResult,handler);}//获取下载歌词的URLprivate void getDownloadLrcURL(final SearchResult searchResult, final Handler handler) {mThreadPool.execute(new Runnable() {@Overridepublic void run() {//http://music.baidu.com/search/lrc?key=%E6%9C%89%E5%BF%83%E4%BA%BA%20G.E.M.%E9%82%93%E7%B4%AB%E6%A3%8B//"http://music.baidu.com/search/lrc?key=" + 歌名 + " " + 歌手//System.out.println("searchResult.getUrl() = " + searchResult.getUrl());//String[] aa = searchResult.getUrl().split("/");//String sn = aa[5];//System.out.println("歌曲编号 = " + sn);//从浏览器复制出来的Url是这样的,"http://music.baidu.com/search?key=%E6%B2%A1%E6%9C%89";//汉字经过utf8编码,比如 冰雨 == %E5%86%B0%E9%9B%A8;//经过测试 获取页面 使用"http://music.baidu.com/search?key=冰雨";无法打开正确连接//比如使用URLEncoder.encode转码,转为utf8//实际使用 获取页面 使用"http://music.baidu.com/search?key=%E6%B2%A1%E6%9C%89";try {String musicName = URLEncoder.encode(searchResult.getMusicName(), "utf8");String artistName = URLEncoder.encode(searchResult.getArtist(), "utf8");//String url = Constant.BAIDU_LRC_SEARCH_HEAD + searchResult.getMusicName() + " " + searchResult.getArtist();String url = Constant.BAIDU_LRC_SEARCH_HEAD + musicName + "+" + artistName;System.out.println("歌词下载页面url = " + url);Document doc = Jsoup.connect(url).userAgent(Constant.USER_AGENT).timeout(6000).get();//System.out.println("歌词下载页面 doc : " + doc);Elements lrcUrls = doc.select("span.lyric-action");System.out.println(lrcUrls);for (int i=0;i<lrcUrls.size();i++) {Elements urlsa = lrcUrls.get(i).getElementsByTag("a");System.out.println("tag a urlsa : " + urlsa);for (int a=0;i<urlsa.size();a++) {System.out.println("----" + urlsa.get(a).toString());String urla = urlsa.get(a).toString();System.out.println("-----" + urla);//-----<a class="down-lrc-btn { 'href':'/data2/lrc/14488216/14488216.lrc' }" href="#">下载LRC歌词</a>if (urla.indexOf("'href':'")>0){String[] uu = urla.split("'href':'");System.out.println("uu1 : " + uu[1]);//uu1 : /data2/lrc/14488216/14488216.lrc' }" href="#">下载LRC歌词</a>String[] uuu = uu[1].split(".lrc");System.out.println("uuu0 : " + uuu[0]);//uuu0 : /data2/lrc/14488216/14488216String result = "http://music.baidu.com" + uuu[0] + ".lrc";System.out.println("result : " + result);//result : http://music.baidu.com/data2/lrc/14488216/14488216.lrcMessage msg = handler.obtainMessage(SUCCESS_LRC,result);msg.sendToTarget();break;}}}} catch (IOException e) {e.printStackTrace();handler.obtainMessage(FAILED_LRC).sendToTarget();}}});}//获取下载音乐的URLprivate void getDownloadMusicURL(final SearchResult searchResult, final Handler handler) {mThreadPool.execute(new Runnable() {@Overridepublic void run() {//http://music.migu.cn/#/album/1003215276//1003215279//http://music.migu.cn/order/1003215279/down/self/P2Z3Y12L1N2/3/001002A/1003215279System.out.println("searchResult.getUrl() = " + searchResult.getUrl());String[] aa = searchResult.getUrl().split("/");String sn = aa[5];System.out.println("歌曲编号 = " + sn);String url = Constant.MIGU_DOWN_HEAD + sn + Constant.MIGU_DOWN_FOOT;System.out.println("歌曲下载页面url = " + url);try {Document doc = Jsoup.connect(url).userAgent(Constant.USER_AGENT).timeout(6000).get();//System.out.println(doc);System.out.println("doc.toString() = " + doc.toString());String[] bb = doc.toString().split("song");//把 下载页面源码 按照"song"分割for (int i=0;i<bb.length;i++){System.out.println("bb[" + i + "] = " + bb[i]);if (bb[i].indexOf("mp3?msisdn")>0){System.out.println("mp3?msisdn = " + bb[i]);String initMp3Url = bb[i];//initMp3Url 初始Mp3下载链接,如下//mp3?msisdn = ":"http://tyst.migu.cn/public/ringmaker01/10月31日中文延期/文件/全套格式/9000首/全曲试听/Mp3_128_44_16/一起走过的日子-刘德华.mp3?msisdn\u003d7b609763f0ff","String[] arrayHttp = initMp3Url.split("http");//把 初始Mp3下载链接 按照"http"分割String[] arrayMp3 = arrayHttp[1].split(".mp3");//把 arrayHttp 按照".mp3"分割String result = "http" + arrayMp3[0] + ".mp3";//把分割去掉的"http"和".mp3",组合回来System.out.println("result");//String result = "http://tyst.migu.cn/public/ringmaker01/10月31日中文延期/文件/全套格式/9000首/全曲试听/Mp3_128_44_16/一起走过的日子-刘德华.mp3";Message msg = handler.obtainMessage(GET_MP3_URL,result);msg.sendToTarget();}}} catch (IOException e) {e.printStackTrace();handler.obtainMessage(GET_FAILED_MP3_URL).sendToTarget();}}});}//下载歌词public void downloadLRC(final String musicName, final String artistName, final Handler handler){mThreadPool.execute(new Runnable() {@Overridepublic void run() {//从浏览器复制出来的Url是这样的,"http://music.baidu.com/search?key=%E6%B2%A1%E6%9C%89";//汉字经过utf8编码,比如 冰雨 == %E5%86%B0%E9%9B%A8;//经过测试 获取页面 使用"http://music.baidu.com/search?key=冰雨";无法打开正确连接//比如使用URLEncoder.encode转码,转为utf8//实际使用 获取页面 使用"http://music.baidu.com/search?key=%E6%B2%A1%E6%9C%89";try {String musicNameEn = URLEncoder.encode(musicName, "utf8");String artistNameEn = URLEncoder.encode(artistName, "utf8");//String url = Constant.BAIDU_LRC_SEARCH_HEAD + searchResult.getMusicName() + " " + searchResult.getArtist();String url = Constant.BAIDU_LRC_SEARCH_HEAD + musicNameEn + "+" + artistNameEn;System.out.println("歌词下载页面url = " + url);Document doc = Jsoup.connect(url).userAgent(Constant.USER_AGENT).timeout(6000).get();//System.out.println("歌词下载页面 doc : " + doc);Elements lrcUrls = doc.select("span.lyric-action");System.out.println(lrcUrls);for (int i = 0; i < lrcUrls.size(); i++) {Elements urlsa = lrcUrls.get(i).getElementsByTag("a");System.out.println("tag a urlsa : " + urlsa);for (int a = 0; a < urlsa.size(); a++) {//System.out.println("----" + urlsa.get(a).toString());String urla = urlsa.get(a).toString();System.out.println("-----" + urla);//-----<a class="down-lrc-btn { 'href':'/data2/lrc/14488216/14488216.lrc' }" href="#">下载LRC歌词</a>if (urla.indexOf("'href':'") > 0) {String[] uu = urla.split("'href':'");System.out.println("uu1 : " + uu[1]);//uu1 : /data2/lrc/14488216/14488216.lrc' }" href="#">下载LRC歌词</a>String[] uuu = uu[1].split(".lrc'");System.out.println("uuu0 : " + uuu[0]);//uuu0 : /data2/lrc/246970367/246970367.lrcString lrcDwonUrl = "http://music.baidu.com" + uuu[0] + ".lrc";System.out.println("lrcDwonUrl : " + lrcDwonUrl);//result : http://music.baidu.com/data2/lrc/14488216/14488216.lrcFile LrcDirFile = new File(Environment.getExternalStorageDirectory() + Constant.DIR_LRC);System.out.println("LrcDirFile : " + LrcDirFile);if (!LrcDirFile.exists()) {LrcDirFile.mkdirs();}String target = LrcDirFile + "/" + musicName + ".lrc";System.out.println("lrcDwonUrl : " + lrcDwonUrl);System.out.println("target : " + target);File fileTarget = new File(target);if (fileTarget.exists()) {handler.obtainMessage(MUSIC_EXISTS).sendToTarget();return;} else {OkHttpClient client = new OkHttpClient();Request request = new Request.Builder().url(lrcDwonUrl).build();Response response = client.newCall(request).execute();if (response.isSuccessful()) {PrintStream ps = new PrintStream(new File(target));byte[] bytes = response.body().bytes();ps.write(bytes, 0, bytes.length);ps.close();handler.obtainMessage(SUCCESS_LRC, target).sendToTarget();}}}}}} catch (IOException e) {e.printStackTrace();}}});}//下载MP3private void downloadMusic(final SearchResult searchResult,final String url,final Handler handler){mThreadPool.execute(new Runnable() {@Overridepublic void run() {File musicDirFile = new File(Environment.getExternalStorageDirectory()+Constant.DIR_MUSIC);if (!musicDirFile.exists()){musicDirFile.mkdirs();}String mp3url = url;//String mp3url = "http://tyst.migu.cn/public/600902-2008430/tone/2008/09/10/2008年9月/4月环球106首歌曲/彩铃/7_mp3-128kbps/等你等到我心痛-张学友.mp3";String target = musicDirFile + "/" + searchResult.getMusicName() + ".mp3";System.out.println(mp3url);System.out.println(target);File fileTarget = new File(target);if (fileTarget.exists()){handler.obtainMessage(MUSIC_EXISTS).sendToTarget();return;}else {//使用OkHttpClient组件OkHttpClient client = new OkHttpClient();Request request = new Request.Builder().url(mp3url).build();System.out.println(request);try {Response response = client.newCall(request).execute();if (response.isSuccessful()){PrintStream ps = new PrintStream(fileTarget);byte[] bytes = response.body().bytes();ps.write(bytes,0,bytes.length);ps.close();handler.obtainMessage(SUCCESS_MP3).sendToTarget();}} catch (IOException e) {e.printStackTrace();handler.obtainMessage(FAILED_MP3).sendToTarget();}}}});}//自定义下载事件监听器public interface OnDownloadListener {public void onDowload(String mp3Url);public void onFailed(String error);}
}
转载请注明出处: http://blog.csdn.net/iwanghang/article/details/51388896
欢迎移动开发爱好者交流
沈阳或周边城市公司有意开发Android,请与我联系
联系方式
微信:iwanghang
QQ:413711276
邮箱:iwanghang@qq.com
沈阳或周边城市公司有意开发Android,请与我联系
联系方式
微信:iwanghang
QQ:413711276
邮箱:iwanghang@qq.com
觉得博文有用,请点赞,请留言,请关注,谢谢!~