一、核心功能
- 获取播放列表
- 播放网络音频
- 进度条及时间
- 切换及暂停
二、功能说明
- 播放列表后台实现
<?php
// 连接数据库
include("conn.php");
// 查询音频播放列表
$res = mysqli_query($link, 'select * from mediaList');
$i = 0;
// 形成JSON格式
echo '[';
while ($row = mysqli_fetch_assoc($res)) {
if ($i != 0) {
echo ',';
}
echo '{"music":"'.$url.$row['music'].'"}';
$i++;
}
echo ']';
mysqli_close($link);
- Android端显示
- Android端播放
- 暂停
- 划屏及按键可实现切换切换
三、主要代码
- AndroidManifest.xml中,给予访问网络资源权限
<uses-permission android:name="android.permission.INTERNET"/>
- 获取播放列表
public class MediaPlay {
// 网络音乐地址
String musicUrl = "";
// 音乐播放列表
String[] musicList;
public MediaPlay() {}
/** 获取播放列表信息 */
public String[] getMusicList() {
HttpURLConnection conn = null;
BufferedReader buf = null;
StringBuilder getRes = new StringBuilder();
String[] res = null;
try {
URL url = new URL(musicUrl);
conn = (HttpURLConnection) url.openConnection();
if (conn.getResponseCode() == 200) {
buf = new BufferedReader(new InputStreamReader(conn.getInputStream()));
for (String s = buf.readLine(); s != null; s = buf.readLine()) {
getRes.append(s);
}
// json处理
JSONArray jsonArray = new JSONArray(getRes.toString());
List<String> list = new ArrayList<>();
for (int i = 0; i < jsonArray.length(); i++) {
list.add(jsonArray.getJSONObject(i).getString("music"));
}
res = list.toArray(new String[list.size()]);
buf.close();
}
} catch (Exception e) {}
musicList = res;
return res;
}
/** 获取播放列表名
* 1. 处理播放列表
*/
public String[] getMusicNameList(String[] musicList) {
int len = musicList.length;
String[] musicNameList = new String[len];
for (int i = 0; i < len; i++) {
String str = musicList[i];
musicNameList[i] = str.substring(str.lastIndexOf("/")+1);
}
return musicNameList;
}
}
- 主界面显示页
组件 | ID |
ListView | mediaList |
// 音频播放列表
ListView mediaList;
String[] playList;
// 实例化 MediaPlay 对象
MediaPlay mp = new MediaPlay();
// 实例化 Bundle 对象
Bundle bundle = new Bundle();
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
/* 选项卡 */
//topTab();
/* 音频播放 */
mediaPlay();
}
/** 线程策略 */
public void waitForRes() {
StrictMode.setThreadPolicy(new StrictMode.ThreadPolicy.Builder().detectDiskReads().detectDiskWrites().penaltyLog().build());
StrictMode.setVmPolicy(new StrictMode.VmPolicy.Builder().detectLeakedSqlLiteObjects().penaltyLog().build());
}
/** 音频播放界面操作
* 1. 播放列表
* 2. 跳转至播放界面
*/
public void mediaPlay() {
mediaList = findViewById(R.id.mediaList);
waitForRes();
playList = mp.getMusicList();
try {
String[] musicNameList = mp.getMusicNameList(playList);
mediaList.setAdapter(new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, musicNameList));
mediaList.setOnItemClickListener(new MusicChoice());
} catch (Exception e) {}
}
/** 播放列表点击事件:
* 1. 跳转至MediaActivity界面
* 2. 传递播放选择信息
*/
class MusicChoice implements AdapterView.OnItemClickListener {
@Override
public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
Intent intent = new Intent(HelperActivity.this, MediaActivity.class);
bundle.putString("index",String.valueOf(i));
bundle.putStringArray("playList",playList);
intent.putExtras(bundle);
startActivity(intent);
}
}
- 播放音频页
组件 | ID | ||
ConstraintLayout | mediaActivity | ||
TextView | musicName | playTime | |
SeekBar | seekBar | ||
ImageButton | playBtn | nextBtn | prevBtn |
ConstraintLayout mediaActivity;
// 触摸事件坐标,阈值
int oldY, newY, oldX, newX, thresholdX = 700, thresholdY = 700;
// 实例化 MediaPlay 对象
MediaPlay mp = new MediaPlay();
// 实例化 MediaPlayer 对象
MediaPlayer player = new MediaPlayer();
// 播放音乐指针
int index;
// 播放列表,播放音乐名列表
String[] playList, mn;
// 播放音乐名,播放时长
TextView musicName, playTime;
// 滚动条
SeekBar seekBar;
// 按键,暂停&播放按键,下一首按键,上一首按键
ImageButton playBtn, nextBtn, prevBtn;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_media);
Toast.makeText(MediaActivity.this, "左划下一首\n右划下一首\n上划退出", Toast.LENGTH_LONG).show();
mediaActivity = findViewById(R.id.mediaActivity);
mediaActivity.setOnTouchListener(new OnTouch());
play();
}
Handler handler = new Handler();
Runnable runnable = new Runnable() {
@Override
public void run() {
// 时间换算
int msec = player.getCurrentPosition(), sec = msec/1000%60, min = msec/1000/60,
totalSec = player.getDuration()/1000, totalMin = totalSec/60;
// 读条
seekBar.setProgress(msec);
// 设置时间
playTime.setText(min+"m"+sec+"s/"+totalMin+"m"+(totalSec%60)+"s");
handler.postDelayed(runnable, 100);
}
};
/** 音乐播放
* 1. 获取从 HelperActivity 传递的音乐播放编号 信息
* 2. 播放音乐
*/
public void play() {
Bundle getMusicInfo = this.getIntent().getExtras();
index = Integer.parseInt(getMusicInfo.getString("index"));
playList = getMusicInfo.getStringArray("playList");
musicName = findViewById(R.id.musicName);
mn = mp.getMusicNameList(playList);
seekBar = findViewById(R.id.seekBar);
playTime = findViewById(R.id.playTime);
playBtn = findViewById(R.id.playBtn);
playBtn.setOnClickListener(new OnPlayClick());
nextBtn = findViewById(R.id.nextBtn);
nextBtn.setOnClickListener(new OnPlayClick());
prevBtn = findViewById(R.id.prevBtn);
prevBtn.setOnClickListener(new OnPlayClick());
setPlayer();
}
/** 重置播放
* 释放上一首的资源
*/
public void resetPlay() {
// 如果已有播放音频,先停止释放资源
if (player.isPlaying()) {
player.stop();
player.reset();
handler.removeCallbacks(runnable);
}
}
/** 设置播放
* 1. 重置播放资源
* 2. 开始播放
*/
public void setPlayer() {
resetPlay();
musicName.setText(mn[index]);
try {
player.setDataSource(playList[index]);
player.prepare();
player.start();
seekBar.setMax(player.getDuration());
handler.post(runnable);
} catch (IOException e) {
e.printStackTrace();
}
}
/** 播放下一首
* 1. 如果前一首是最后一首,则重新播放第一首
*/
public void nextPlay() {
index = (index + 1) % playList.length;
setPlayer();
}
/** 播放下一首
* 1. 如果前一首是第一首,则播放最后一首
*/
public void prevPlay() {
index = (index - 1 + playList.length) % playList.length;
setPlayer();
}
/** 划屏触摸事件:
* 左划,下一首
* 右划,上一首
* 上划,退出,返回 主界面
*/
class OnTouch implements View.OnTouchListener {
@Override
public boolean onTouch(View view, MotionEvent motionEvent) {
if (motionEvent.getAction() == MotionEvent.ACTION_DOWN) {
oldY = (int) motionEvent.getY();
oldX = (int) motionEvent.getX();
return true;
}
if (motionEvent.getAction() == MotionEvent.ACTION_UP) {
newY = (int) motionEvent.getY();
newX = (int) motionEvent.getX();
// 上划退出,重置播放资源
if (oldY - newY > thresholdY) {
resetPlay();
startActivity(new Intent(MediaActivity.this, MainActivity.class));
return true;
}
// 播放下一首音乐
if (oldX - newX > thresholdX) {
nextPlay();
return true;
}
// 播放上一首音乐
if (newX - oldX > thresholdX) {
prevPlay();
return true;
}
return true;
}
return false;
}
}
/** 音频按键事件:
* 1. playBtn 如果在播放 暂停; 如果暂停 播放, 滚动条继续监听
* 2. nextBtn 下一首
* 3. prevBtn 上一首
*/
class OnPlayClick implements View.OnClickListener {
@Override
public void onClick(View view) {
if (view == playBtn) {
try {
if (player.isPlaying()) {
player.pause();
} else {
player.start();
handler.post(runnable);
}
} catch (Exception e) {}
} else if (view == nextBtn) {
nextPlay();
} else if (view == prevBtn) {
prevPlay();
}
}
}