Android 音频播放器

该博客详细介绍了如何在Android平台上实现音频播放功能,包括获取播放列表、播放网络音频、进度条显示、暂停播放以及通过滑动切换音频。主要涉及PHP后台生成JSON格式的播放列表,以及Android端的HTTP请求获取列表、UI展示、音乐播放控制和触摸事件处理。
摘要由CSDN通过智能技术生成

一、核心功能

  1. 获取播放列表
  2. 播放网络音频
  3. 进度条及时间
  4. 切换及暂停

二、功能说明

  1. 播放列表后台实现
<?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);
  1. Android端显示
    播放列表
  2. Android端播放
    播放1
  • 暂停
    播放2
  • 划屏及按键可实现切换切换
    播放3

三、主要代码

  1. AndroidManifest.xml中,给予访问网络资源权限
<uses-permission android:name="android.permission.INTERNET"/>
  1. 获取播放列表
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;
    }
}
  1. 主界面显示页
组件ID
ListViewmediaList
// 音频播放列表
	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);
        }
    }
  1. 播放音频页

流程

组件ID
ConstraintLayoutmediaActivity
TextViewmusicNameplayTime
SeekBarseekBar
ImageButtonplayBtnnextBtnprevBtn
    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();
            }
        }
    }
音频播放实现暂停开始等 }); btnStop.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { // TODO Auto-generated method stub musicStop(); } }); player.setOnCompletionListener(new OnCompletionListener() { @Override public void onCompletion(MediaPlayer mp) { // TODO Auto-generated method stub if(currentPlayMusicNum<musicList.size()){ currentPlayMusicNum+=1; }else{ currentPlayMusicNum=0; } musicStart(currentPlayMusicNum); } }); lvShowMusicList.setOnItemClickListener(new OnItemClickListener() { @SuppressLint("ResourceAsColor") @Override public void onItemClick(AdapterView parent, View view, int position, long id) { if(saveView==view){ saveView.setBackgroundResource(R.color.nocolor); currentPlayMusicNum=0; } else{ if(saveView!=null) saveView.setBackgroundResource(R.color.nocolor); view.setBackgroundResource(R.color.colorblue); saveView=view; currentPlayMusicNum=position; musicStart(currentPlayMusicNum); } //id_this=position; } }); sb.setOnSeekBarChangeListener(new OnSeekBarChangeListener() { @Override public void onStopTrackingTouch(SeekBar seekBar) { // TODO Auto-generated method stub } @Override public void onStartTrackingTouch(SeekBar seekBar) { // TODO Auto-generated method stub } @Override public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) { // TODO Auto-generated method stub if(fromUser){ sb.setProgress(progress); //musicPause(); MusicModel music=musicList.get(currentPlayMusicNum); music.setPlayTime(music.getAllTime()*progress/100); //pausePosition=(int) (music.getAllTime()*progress/100); player.seekTo((int) music.getPlayTime()); player.start(); } } }); }
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值