andriod 简易音乐盒开发实现上一曲、下一曲、暂停、自动播放下一曲(第二篇具体实现)

本文介绍了一个简单的在线音乐播放器的开发过程,包括音乐列表界面、音乐服务实现、主界面功能实现等关键部分的代码实现,并提供了音乐文件的下载功能。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

    mp3抽象类

package com.example.onlinemusicbox;

public class Mp3Info{
private String songName;//歌曲名
private long Id;//序列号
private String Artist;//艺术家名
private long Duration;
private long Size; //歌曲大小
private String Url;//歌曲地址


public String getSongName() {
return songName;
}
public void setSongName(String songName) {
this.songName = songName;
}
public long getId() {
return Id;
}
public void setId(long id) {
this.Id = id;
}
public String getArtist() {
return Artist;
}
public void setArtist(String artist) {
this.Artist = artist;
}
public long getDuration() {
return Duration;
}
public void setDuration(long duration) {
this.Duration = duration;
}
public long getSize() {
return Size;
}
public void setSize(long size) {
this.Size = size;
}
public String getUrl() {
return Url;
}
public void setUrl(String url) {
this.Url = url;
}
   

}

列表界面代码

package com.example.onlinemusicbox;


import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;


import android.app.Activity;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.TextView;
import android.widget.Toast;
/*
 * 列表界面的服务方法
 * 
 */
public class MusicListActivity extends Activity{


private ImageView iv_back;
private ListView mMusiclist;                   //音乐列表


private myListAdapter myAdapter;
private TextView music_Num;
private TextView music_Name;
private TextView music_Artist;
private ImageView music_Menu;
private static Handler handler;
private static  String path;
static ArrayList<Mp3Info> mp3Infos = new ArrayList<Mp3Info>();


protected void onCreate(Bundle savedInstanceState) {

super.onCreate(savedInstanceState);
//Intent intent=getIntent();

setContentView(R.layout.music_list);
iv_back=(ImageView)findViewById(R.id.iV_back);
mMusiclist = (ListView) findViewById(R.id.musicList);
    myAdapter=new myListAdapter();   
//为ListView添加数据源
    mp3Infos = MusicUtil.getMp3Infos(getApplicationContext());  //获取歌曲对象集合
    //setListAdpter(MusicUtil.getMusicMaps(mp3Infos));    //显示歌曲列表
    mMusiclist.setAdapter(myAdapter);
    mMusiclist.setOnItemClickListener(new OnItemClickListener() {


     public void onItemClick(AdapterView<?> parent, View view, int position,
    long id) {
    Intent intent = new Intent(MusicListActivity.this,
    MainActivity.class);
    path=mp3Infos.get(position).getUrl();
   
    intent.putExtra("path", path);// 传地址
    intent.putExtra("current_position",position);
    startActivity(intent);
MusicListActivity.this.finish();


    }
});
     handler=new Handler(){

public void handleMessage(android.os.Message msg){
switch(msg.what){
case 100:
Toast.makeText(MusicListActivity.this, "now the path is"+path, 0).show();
break;

default:
break;
}

};
};
    iv_back.setOnClickListener(new OnClickListener() {


public void onClick(View view) {
startActivity(new Intent(MusicListActivity.this,MainActivity.class));
MusicListActivity.this.finish();
}
});
    
   
    
 
}
/**
     * 创建数据适配器继承baseadapter
     * 
     */
    class myListAdapter extends BaseAdapter{


/**
*  返回item总数
*/
public int getCount() {

return mp3Infos.size();
}


//获得item代表的对象
public Object getItem(int position) {

return mp3Infos.get(position);
}


//获得item的id
public long getItemId(int position) {

return position;
}
//获得item的试图
public View getView(int position, View convertview, ViewGroup parent) {
//找到musicitem。xml文件并转换成view 对象
View view=View.inflate(MusicListActivity.this, R.layout.music_item, null);
//找到musicitem中的textview和imagview
music_Artist=(TextView)view.findViewById(R.id.music_Artist);
music_Artist.setText(mp3Infos.get(position).getArtist());
music_Num=(TextView)view.findViewById(R.id.number);
music_Num.setText(mp3Infos.get(position).getId()+"");
music_Name=(TextView)view.findViewById(R.id.music_name);
music_Name.setText(mp3Infos.get(position).getSongName());
music_Menu=(ImageView)view.findViewById(R.id.music_menu);
music_Menu.setBackgroundResource(R.drawable.menu_play);
return view;
};
}


  

}


音乐服务的实现代码

package com.example.onlinemusicbox;
import java.io.IOException;


import android.app.Service;
import android.content.Intent;
import android.media.AudioManager;
import android.media.MediaPlayer;
import android.media.MediaPlayer.OnCompletionListener;
import android.media.MediaPlayer.OnPreparedListener;
import android.os.Binder;
import android.os.IBinder;
import android.widget.Toast;


public class MusicService extends Service {
public static MediaPlayer mediaPlayer=new MediaPlayer();
public static final String TAG="MusicService";


class MyBinder extends Binder{
//指定参数为音频文件

public MediaPlayer getThePlayer(){
return mediaPlayer;
}
//播放音乐
public void plays(String path){
play(path);
}

public void pauses(){
pause();
}
// public void stops(){
// stop();
// }
//获取当前播放进度
public int getCurrentPosition(){
return getCurrentProgress();
}
//get music length
public int getMusicWidth(){

return getMusicLength();
}
public boolean isPlayings(){

return isPlaying();
}
}

public void onCreate(){

super.onCreate();
}




//播放音乐

public void play(String path) {

try{

//指定参数为音频文件
mediaPlayer.reset();
mediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
//setting the path

mediaPlayer.setDataSource(path);
//prepare for play
mediaPlayer.prepare();
mediaPlayer.setOnPreparedListener(new OnPreparedListener() {


public void onPrepared(MediaPlayer mp) {

//start play
mediaPlayer.start();
}
});
}catch(Exception e){
e.printStackTrace();
}
}

public boolean isPlaying(){
return mediaPlayer.isPlaying();

}

//play pause
public void pause(){
if( mediaPlayer.isPlaying()){
//Log.i(TAG, "play pause");
mediaPlayer.pause();
}else if(!(mediaPlayer.isPlaying())){
mediaPlayer.start();
}
}
// public void stop(){
// if(mediaPlayer !=null)
// {
// //Log.i(TAG, "stop play");
// mediaPlayer.stop();
// //mediaPlayer.release();
// //mediaPlayer=null;
//
// }else{
// Toast.makeText(getApplicationContext(), "already stoped", 0).show();
// }
// }
//get resources length
public int getMusicLength(){

if(mediaPlayer !=null){
return mediaPlayer.getDuration();
}
return 0;
}
//get current progress 进度
public int getCurrentProgress(){

try{
if(mediaPlayer !=null){

if(mediaPlayer.isPlaying()){
//Log.i("MusicService","获取当前进度");
return mediaPlayer.getCurrentPosition();
}else if(!mediaPlayer.isPlaying()){

return mediaPlayer.getCurrentPosition();
}
}
}catch(Exception e){

}
return 0;
}

public void onDestroy(){
if(mediaPlayer!=null){
mediaPlayer.stop();
mediaPlayer.release();
mediaPlayer=null;
}
super.onDestroy();
}





public IBinder onBind(Intent intent) {

return new MyBinder();
}
}


音乐工具类

package com.example.onlinemusicbox;


import android.content.Context;
import android.database.Cursor;
import android.provider.MediaStore;


import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
 
public class MusicUtil {
    /**
     * 用于从数据库中查询歌曲的信息,保存在List当中
     *
     * @return
     */
    public static ArrayList<Mp3Info> getMp3Infos(Context context) {
        Cursor cursor = context.getContentResolver().query(
                MediaStore.Audio.Media.EXTERNAL_CONTENT_URI, null, null, null,
                MediaStore.Audio.Media.DEFAULT_SORT_ORDER);
        ArrayList<Mp3Info> mp3Infos = new ArrayList<Mp3Info>();
        for (int i = 0; i < cursor.getCount(); i++) {
            cursor.moveToNext();
            Mp3Info mp3Info = new Mp3Info();
            long id = cursor.getLong(cursor
                    .getColumnIndex(MediaStore.Audio.Media._ID));               //音乐id
            String title = cursor.getString((cursor
                    .getColumnIndex(MediaStore.Audio.Media.TITLE)));            //音乐标题
            String artist = cursor.getString(cursor
                    .getColumnIndex(MediaStore.Audio.Media.ARTIST));            //艺术家
            long duration = cursor.getLong(cursor
                    .getColumnIndex(MediaStore.Audio.Media.DURATION));          //时长
            long size = cursor.getLong(cursor
                    .getColumnIndex(MediaStore.Audio.Media.SIZE));              //文件大小
            String url = cursor.getString(cursor
                    .getColumnIndex(MediaStore.Audio.Media.DATA));              //文件路径
            int isMusic = cursor.getInt(cursor
                    .getColumnIndex(MediaStore.Audio.Media.IS_MUSIC));          //是否为音乐
            if (isMusic != 0) {     //只把音乐添加到集合当中
                mp3Info.setId(id);
                mp3Info.setSongName(title);
                mp3Info.setArtist(artist);
                mp3Info.setDuration(duration);
                mp3Info.setSize(size);
                mp3Info.setUrl(url);
                mp3Infos.add(mp3Info);
            }
        }
        cursor.close();
        return mp3Infos;
    }
 

    }


文件保存工具类(可用来实现网络下载功能)

package com.example.onlinemusicbox;


import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;


public class FileUtil {
//创建目录
public static File createDir(String path,String dir){
File file = new File(path,dir);
if(!file.exists()){
if(file.mkdirs()){
}
}
return file;
}
//创建文件
public static File createFile(File path,String src) throws IOException{
File file = new File(path,src);
if(!file.exists()){
if(file.createNewFile()){
}
}
return file;
}
//保存文件到SDK
public static void saveSDKFile(File file,InputStream is) throws IOException{

FileOutputStream fos = new FileOutputStream(file);
byte[] buffer = new byte[1024];
int len = 0;
while(-1 != (len = is.read(buffer))){
fos.write(buffer, 0, len);
fos.flush();
}
fos.close();
is.close();
}
}

     主界面实现

package com.example.onlinemusicbox;


import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;
import java.util.Random;


import android.app.Activity;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.ServiceConnection;
import android.media.AudioManager;
import android.media.MediaPlayer;
import android.media.MediaPlayer.OnCompletionListener;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.IBinder;
import android.os.Message;
import android.text.TextUtils;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.ImageView;
import android.widget.RadioButton;
import android.widget.SeekBar;
import android.widget.SeekBar.OnSeekBarChangeListener;
import android.widget.TextView;
import android.widget.Toast;


import com.example.onlinemusicbox.MusicService.MyBinder;




public class MainActivity extends Activity implements OnClickListener{



private static int position=0;// 播放位置
private static int currentVolume=5;// 播放位置
private AudioManager audioManager=null; 
private static enum play_modes{random,list_play,single};
private play_modes playmode=play_modes.single; //播放模式
    private ImageView iv_play_menu;
private ImageView iv_list_menu;
private ImageView iv_artist_pic;
private TextView tv_music_name;
private TextView tv_artist_name;
private TextView playing_name;
private static int pauseposition=0;
private SeekBar skb;
private SeekBar skb_sound;
private ImageView  btn_play;
private ImageView  btn_prev;
private ImageView  btn_next;
private RadioButton rd_radom;
private RadioButton rd_list;
private RadioButton rd_single;
private TextView bt_play_online;
ArrayList<Mp3Info> mp3Infos = new ArrayList<Mp3Info>();
private ImageView  btn_pause;
private ImageView btn_download;
private ImageView btn_playonline;
//private ImageView iv_seach;
private Intent intent;
private myConn conn;
private Thread mThread;
private ImageView iv_pic;
MyBinder binder;
private TextView tv_music_length;
private TextView tv_music_current;
private int  currentMusicIndex=0;


File dir;
//private static final String auto_music_name="西瓜JUN - 清明上河图.mp3";

private static final String path="http://192.168.253.1:8080/%E6%88%91%E4%B8%8D%E5%AF%B9.mp3" ;

private String musicPath;
private Handler handler=new Handler(){

public void handleMessage(android.os.Message msg){
switch(msg.what){
case 100:
int currentPosition=(Integer) msg.obj;
skb.setProgress(currentPosition);
tv_music_current.setText(timeParse(currentPosition));
break;
case 404:
Toast.makeText(MainActivity.this, "cannot find the file", 0).show();
break;
case 101:
Toast.makeText(MainActivity.this, "开始下载"+getfileName(path), 0).show();break;
case 102:
Toast.makeText(MainActivity.this, getfileName(path)+"下载完成", 0).show();break;

default:
break;
}

};
};



protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
initial();
intent=getIntent();
if(intent.hasExtra("path")&&intent.hasExtra("current_position")){
//Toast.makeText(this, "get the path", 0).show();
musicPath=intent.getStringExtra("path");
position=intent.getIntExtra("current_position", 0);
Message message=Message.obtain();
message.what=103;
handler.sendMessage(message);


}
    iv_list_menu.setOnClickListener(new OnClickListener() {

public void onClick(View v) {
Intent intent1=new Intent();
intent1.setClass(MainActivity.this, MusicListActivity.class);
startActivity(intent1);

}
});
intent=new Intent(this, MusicService.class);
bindService(intent, conn, BIND_AUTO_CREATE);
 


}
private void initial() {
iv_artist_pic=(ImageView)findViewById(R.id.iv_artist_pic);
tv_music_name=(TextView)findViewById(R.id.tv_music_name);
tv_artist_name=(TextView)findViewById(R.id.tv_music_artist_name);
iv_play_menu=(ImageView)findViewById(R.id.iV_menu_play);
iv_list_menu=(ImageView)findViewById(R.id.iV_musicList);
playing_name=(TextView)findViewById(R.id.TV_playingName);
skb=(SeekBar)findViewById(R.id.seekBar1);
btn_play=(ImageView)findViewById(R.id.bt_play);
btn_prev=(ImageView)findViewById(R.id.bt_before);
btn_next=(ImageView)findViewById(R.id.bt_next);
btn_pause=(ImageView)findViewById(R.id.bt_pause);
btn_playonline=(ImageView)findViewById(R.id.bt_playOnline);
mp3Infos = MusicUtil.getMp3Infos(getApplicationContext());  //获取歌曲对象集合
iv_artist_pic=(ImageView)findViewById(R.id.iv_artist_pic);
//btn_download=(ImageView)findViewById(R.id.);
rd_list=(RadioButton)findViewById(R.id.rd_list);
rd_radom=(RadioButton)findViewById(R.id.rd_radom);
rd_single=(RadioButton)findViewById(R.id.rd_single);
iv_pic=(ImageView)findViewById(R.id.iV_pic);
tv_music_length=(TextView)findViewById(R.id.music_time_length);
tv_music_current=(TextView)findViewById(R.id.music_current_time);
skb_sound=(SeekBar)findViewById(R.id.skb_sound);
btn_play.setOnClickListener(this);
btn_prev.setOnClickListener(this);
btn_next.setOnClickListener(this);
btn_pause.setOnClickListener(this);
btn_playonline.setOnClickListener(this);
audioManager = (AudioManager) getSystemService(Context.AUDIO_SERVICE);
skb_sound.setMax(30);
skb.setOnSeekBarChangeListener(new OnSeekBarChangeListener() {


public void onStopTrackingTouch(SeekBar skb) {
//获取拖动后的位置
int progress=skb.getProgress();
//调用binder中的getplayer(与play中的mediaplayer是同一个) 让它跳转到指定位置播放
binder.getThePlayer().seekTo(progress);

}


public void onStartTrackingTouch(SeekBar arg0) {


}


public void onProgressChanged(SeekBar skb, int arg1, boolean arg2) {


}
});
skb_sound.setOnSeekBarChangeListener(new OnSeekBarChangeListener() {


public void onStopTrackingTouch(SeekBar skb) {


}


public void onStartTrackingTouch(SeekBar arg0) {


}


public void onProgressChanged(SeekBar skb, int progress, boolean fromUser) {

currentVolume=progress;
   audioManager.setStreamVolume(AudioManager.STREAM_MUSIC, progress, 0);


}
});
rd_list.setOnClickListener(new OnClickListener() {

//选中就将全局变量播放模式改为列表播放
public void onClick(View view) {
playmode=play_modes.list_play;
}
});
rd_single.setOnClickListener(new OnClickListener() {

//选中就将全局变量播放模式改为单曲播放
public void onClick(View view) {
playmode=play_modes.single;
}
});
rd_radom.setOnClickListener(new OnClickListener() {

//选中就将全局变量播放模式改为random播放
public void onClick(View view) {
playmode=play_modes.random;
}
});

//btn_download.setOnClickListener(this);

iv_play_menu=(ImageView)findViewById(R.id.iV_menu_play);
iv_list_menu=(ImageView)findViewById(R.id.iV_musicList);
conn=new myConn();
dir = FileUtil.createDir(Environment.getExternalStorageDirectory().getAbsolutePath(), "mymusic");

 
}

//set the seekbar's length get music's length
private void initSeekBar(){

int musicWidth=binder.getMusicWidth();
skb.setMax(musicWidth);


}
//更新播放进度
private  void UpdateProgress(){

mThread =new Thread(){
public void run(){
while(!interrupted()){
//调用服务当中的函数获取当前播放进度
int currentposition=binder.getCurrentPosition();

Message message=Message.obtain();
message.obj=currentposition;
message.what=100;
handler.sendMessage(message);
binder.getThePlayer().setOnCompletionListener(new OnCompletionListener() {


public void onCompletion(MediaPlayer mp) {

next();
}
});
}
};
};
mThread.start();

}

public class myConn implements ServiceConnection{



public void onServiceConnected(ComponentName name, IBinder service) {
binder=(MyBinder) service;

}



public void onServiceDisconnected(ComponentName arg0) {

}

}

// public  void playOnline(){
// final MediaPlayer mediaplayer=MediaPlayer.create(MainActivity.this, Uri.parse(path));
// mediaplayer.reset();
// playing_name.setText(getfileName(path));
// try {
// mediaplayer.prepare();
// } catch (IllegalStateException | IOException e) {
//
// e.printStackTrace();
// }
// mediaplayer.start();
// mediaplayer.setOnCompletionListener(new OnCompletionListener() {
//
// @Override
// public void onCompletion(MediaPlayer arg0) {
// mediaplayer.reset();
//
// }
// });
// }
/*
* 按钮点击事件处理函数
*/

public void onClick(View v) {


 
switch(v.getId()){

case R.id.bt_play:
myplay(mp3Infos.get(position).getUrl());
btn_play.setImageResource(R.drawable.pause);
break;
case R.id.bt_before:
previous();

btn_play.setImageResource(R.drawable.pause);

break;
case R.id.bt_next:
next();
btn_play.setImageResource(R.drawable.pause);

break;
case R.id.bt_pause:
binder.pauses();
if(binder.isPlayings()){
btn_play.setImageResource(R.drawable.pause);
}else{
btn_play.setImageResource(R.drawable.play);
}
break;
case R.id.bt_playOnline:
binder.plays(path);

break;
// case R.id.bt_download:
// new Thread() {
// public void run() {
// //MainActivity.this.download();
// MainActivity.this.download2();
//
// };
// }.start();
// //MainActivity.this.download2();
//
// break;
default:
break;
}

}


//play and pause
private void myplay(String playpath) {
if(!TextUtils.isEmpty(playpath)){
binder.plays(playpath);
String length=timeParse(binder.getMusicWidth());
tv_music_length.setText(length);
showDetail();
initSeekBar();
UpdateProgress();
}else{
Toast.makeText(this, "找不到音乐文件", 0).show();
}
}


//单曲循环
    private void single() {
        currentMusicIndex++;
        currentMusicIndex--; 
        myplay(mp3Infos.get(currentMusicIndex).getUrl());
        showDetail(currentMusicIndex);
    }
 
    //随机播放方法
    private void random() {
        currentMusicIndex = new Random().nextInt(mp3Infos.size());
        
        myplay(mp3Infos.get(currentMusicIndex).getUrl());
        showDetail(currentMusicIndex);
    }
 
    //列表循环
    private void listPlay() {
        currentMusicIndex++;
        if (currentMusicIndex >= mp3Infos.size()) {
            currentMusicIndex = 0;
        } 
        myplay(mp3Infos.get(currentMusicIndex).getUrl());
        showDetail(currentMusicIndex);
    }
 


//播放上一曲
    private void previous() {
 
 
        //判断是否为第一首歌曲,若为第一首歌曲,则播放最后一首
        if (playmode==play_modes.single) {
            single();
        } else {
            //当前音乐播放位置--(上一曲)
            currentMusicIndex--;
            if (currentMusicIndex <= 0) {
                Toast.makeText(MainActivity.this, "已经是第一首了", Toast.LENGTH_SHORT).show();
                return;
            } else {


                //播放
                myplay(mp3Infos.get(currentMusicIndex).getUrl());
                showDetail(currentMusicIndex);
            }
        }
    }
 
    //播放下一曲(与上一曲类似)
    private void next() {
        if (playmode==play_modes.random) {
            random();
 
        } else if (playmode==play_modes.single) {
            single();
 
        } else if (playmode==play_modes.list_play) {
            listPlay();
 
        } else {
            currentMusicIndex++;
            if (currentMusicIndex >= mp3Infos.size()) {
                Toast.makeText(MainActivity.this, "已经是最后一首了", Toast.LENGTH_SHORT).show();
                return;
            } else {
        
                myplay(mp3Infos.get(currentMusicIndex).getUrl());
                showDetail(currentMusicIndex);
            }
        }
    }
private void showDetail() {
playing_name.setText(mp3Infos.get(position).getSongName());
tv_music_name.setText(mp3Infos.get(position).getSongName());
tv_artist_name.setText(mp3Infos.get(position).getArtist());
}
private void showDetail(int position) {
playing_name.setText(mp3Infos.get(position).getSongName());
tv_music_name.setText(mp3Infos.get(position).getSongName());
tv_artist_name.setText(mp3Infos.get(position).getArtist());
}
public void onDestroy(){
//如果线程没有退出,则退出
if(mThread!=null){
if(mThread.isInterrupted())
mThread.interrupt();

}
unbindService(conn);
super.onDestroy();
}

private void download2() {        //下载函数,需要事先定义好url ,该函数会根据url去下载,下载开始会发送101通知主线程开始下载,通知下载完成时会发送消息102通知主线程下载完成,读者可以自己用tomcat搭建一个服务器用来测试

try {
URL url = new URL(path);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setDoInput(true);
conn.setConnectTimeout(5000);

InputStream is = conn.getInputStream();
Message message=Message.obtain();
message.what=101;
handler.sendMessage(message);
File dir = FileUtil.createDir(Environment.getExternalStorageDirectory().getAbsolutePath(), "mymusic");
File src = FileUtil.createFile(dir, getfileName(path));
FileUtil.saveSDKFile(src, is);
Message message2=Message.obtain();
message2.what=102;
handler.sendMessage(message2);
} catch (MalformedURLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}

}
private static String getfileName(String url) { //根据url获取文件的名字和后缀名方法 
String fileName="";
String name=url.substring(url.lastIndexOf('/')+1);


try {
fileName=java.net.URLDecoder.decode(new String(name.getBytes("ISO-8859-1"), "UTF-8"), "UTF-8");
} catch (UnsupportedEncodingException e) {

e.printStackTrace();
}
 return fileName;
   }  
//音乐名获得函数
private static String getmusicName(String url) { //根据url获取文件的名字和后缀名方法 
String name="";
 name=url.substring(url.lastIndexOf('/')+1);
return name;
}
//时间转换函数,将获取的音频时长及当前长度转换
 public static String timeParse(int duration) {  
       String time = "" ;  
       long minute = duration / 60000 ;  
       long seconds = duration % 60000 ;  
       long second = Math.round((float)seconds/1000) ;  
       if( minute < 10 ){  
           time += "0" ;  
       }  
       time += minute+":" ;  
       if( second < 10 ){  
           time += "0" ;  
       }  
       time += second ;  
       return time ;  
   }  
}




 

 由于作者是初学者,写这个音乐盒的时候查过许多网络相关资料,若有侵权行为请联系作者删除

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值