AS广播实现音乐播放器

项目要求

  1. 有播放、暂停、停止功能
  2. 有上一首和下一首功能
  3. 显示歌名及歌手

项目效果展示

在这里插入图片描述

核心代码

主页面布局文件

在这里插入图片描述

MainActivity

  1. 定义的变量
    TextView title, author;
    ImageButton play, stop,last,next;

    ActivityReceiver activityReceiver;

    public static final String CTL_ACTION=
            "org.crazyit.action.CTL_ACTION";
    public static final String UPDATE_ACTION=
            "org.crazyit.action.UPDATE_ACTION";
    int status = 0x11;
    String[] titleStrs = new String[] {"MOM","夏天的风","微微","I don't wanna see u anymore"};
    String[] authorStrs = new String[] {"蜡笔小新","温岚","傅如乔","NINEONE"};

  1. onCreate()函数
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        activityReceiver = new ActivityReceiver();
        IntentFilter filter = new IntentFilter();
        //指定BroadCastReceiver监听的action
        filter.addAction(UPDATE_ACTION);
        registerReceiver(activityReceiver,filter);
        Intent intent = new Intent(this,MusicService.class);

        startService(intent);

        //找到对应控件
        play = this.findViewById(R.id.imgplay);
        stop = this.findViewById(R.id.imgstop);
        next = this.findViewById(R.id.imgnext);
        last = this.findViewById(R.id.imglast);
        title = this.findViewById(R.id.txttitle);
        author = this.findViewById(R.id.txtauthor);
        //添加监听
        play.setOnClickListener(this);
        stop.setOnClickListener(this);
        next.setOnClickListener(this);
        last.setOnClickListener(this);


    }

  1. onClick()函数
    @Override
    public void onClick(View view) {
        Intent intent = new Intent("org.crazyit.action.CTL_ACTION");
        //在主界面按下对应按钮,传递给service对应参数
        switch (view.getId())
        {
            case R.id.imgplay:
                intent.putExtra("control",1);
                break;
            case R.id.imgstop:
                intent.putExtra("control",2);
                break;
            case R.id.imgnext:
                intent.putExtra("control",3);
                break;
            case R.id.imglast:
                intent.putExtra("control",4);
                break;
        }
        sendBroadcast(intent);

    }
  1. ActivityReceiver()函数
    private class ActivityReceiver extends BroadcastReceiver{

        @Override
        public void onReceive(Context context, Intent intent) {
            //获取来自receive中intent的update消息,代表播放状态
            int update = intent.getIntExtra("update",-1);
            //获取来自receive中intent的curruent消息,代表正在播放的歌曲
            int current = intent.getIntExtra("current",-1);
            //如果状态为正在播放歌曲或暂停
            if(current>=0&&(update == 0x12||update == 0x13||update==0x14))
            {
                title.setText(titleStrs[current]);
                author.setText(authorStrs[current]);
            }
            //如果状态为未播放歌曲
            else
            {
                title.setText("未播放歌曲");
                author.setText("未播放歌曲");
            }
            switch (update)
            {
                //如果未播放歌曲,则播放图标为播放
                case 0x11:
                    play.setImageResource(R.drawable.play);
                    status=0x11;
                    break;
                //如果正在播放歌曲,则播放图标为暂停
                case 0x12:
                    play.setImageResource(R.drawable.pause);
                    status=0x12;
                    break;
                case 0x13:
                    play.setImageResource(R.drawable.play);
                    status=0x13;
                    break;
                case 0x14:
                    break;
            }

        }
    }

MusicService

  1. 定义的变量
MyReceiver serviceReceiver;
    AssetManager am;
    String[] musics=new String[]{"music0.mp3","music1.mp3","music2.mp3","music3.mp3"};
    MediaPlayer mPlayer;
    //0x11表示没有播放,0x12代表正在播放,0x13代表暂停
    int status=0x11;
    int current=0;
  1. onCreate()函数
   public void onCreate(){
        super.onCreate();
        am=getAssets();
        //创建BroadcastReceiver
        serviceReceiver=new MyReceiver();
        //创建IntentFilter
        IntentFilter filter=new IntentFilter();
        filter.addAction(MainActivity.CTL_ACTION);
        registerReceiver(serviceReceiver,filter);
        mPlayer=new MediaPlayer();
        //为MediaPlayer播放完成事件绑定监听器
        mPlayer.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
            @Override
            public void onCompletion(MediaPlayer mp) {
                current++;
                if (current>=4)
                {
                    current=0;
                }
                Intent sendIntent = new Intent(MainActivity.UPDATE_ACTION);
                sendIntent.putExtra("update",0x14);
                sendIntent.putExtra("current",current);
                //发送广播,将被Activity组件中的BroadcastReceiver接收
                sendBroadcast(sendIntent);
                //准备播放音乐
                prepareAndPlay(musics[current]);
            }
        });
    }
  1. MyReceiver类里的onReceive()函数
    public class MyReceiver extends BroadcastReceiver{

        @Override
        public void onReceive(Context context, Intent intent) {
            int control =intent.getIntExtra("control",-1);
            switch (control)
            {
                //播放或暂停
                case 1:
                    //原来处于没有播放状态
                    if (status==0x11)
                    {
                        //准备并播放音乐
                        prepareAndPlay(musics[current]);
                        status=0x12;
                    }
                    //原来处于播放状态
                    else if (status==0x12)
                    {
                        //暂停
                        mPlayer.pause();
                        //改变为暂停状态
                        status=0x13;
                    }
                    //原来处于暂停状态
                    else if (status==0x13)
                    {
                        //播放
                        mPlayer.start();
                        //改变状态
                        status=0x12;
                    }
                    break;
                //停止声音
                case 2:
                    //如果原来正在播放或暂停
                    if (status==0x12||status==0x13) {
                        //停止播放
                        mPlayer.stop();
                        status = 0x11;
                    }
                    break;
                case 3:
                    //原来处于没有播放或暂停状态
                    if (status==0x11||status==0x13)
                    {
                        if(current==0) {
                            current=3;
                            prepareAndPlay(musics[current]);
                        }
                        //准备并播放音乐
                        else {
                            current=current-1;
                            prepareAndPlay(musics[current]);
                        }
                        status=0x12;
                    }
                    //原来处于播放状态
                    else if (status==0x12)
                    {
                        //上一首//准备并播放音乐
                        if(current==0) {
                            current=3;
                            prepareAndPlay(musics[current]);
                        }
                        else {
                            current=current-1;
                            prepareAndPlay(musics[current]);
                        }
                    }
                    break;
                case 4:
                    //原来处于没有播放或暂停状态
                    if (status==0x11||status==0x13)
                    {
                        if(current==3) {
                            current=0;
                            prepareAndPlay(musics[current]);
                        }   //准备并播放音乐
                        else {
                            current=current+1;
                            prepareAndPlay(musics[current]);
                        }
                        status=0x12;
                    }
                    else if (status==0x12)
                    {
                        if(current==3) {
                            current=0;
                            prepareAndPlay(musics[current]);
                        }
                        else {
                            current=current+1;
                            prepareAndPlay(musics[current]);
                        }
                    }
                    break;
            }
            //广播通知Activity更改图标、文本框
            Intent sendIntent=new Intent(MainActivity.UPDATE_ACTION);
            sendIntent.putExtra("update",status);
            sendIntent.putExtra("current",current);
            //发送广播,将被Activity组件中的BroadcastReceiver接收
            sendBroadcast(sendIntent);
        }
        }
  1. prepareAndPlay()函数
    private void prepareAndPlay(String music)
    {
        try
        {
            //打开指定音乐文件
            AssetFileDescriptor afd=am.openFd(music);
            mPlayer.reset();
            //使用MediaPlayer加载指定的音乐文件
            mPlayer.setDataSource(afd.getFileDescriptor(),afd.getStartOffset(),afd.getLength());
            //准备声音
            mPlayer.prepare();
            //播放
            mPlayer.start();
        }catch (IOException e) {
            e.printStackTrace();
        }
    }

项目总结

本次项目实现了音乐的播放、暂停、切换等功能,Service与之前学的Activity有相似之处,经过对比巩固加深了之前的知识。广播组件是新的一种信息传递的方式,对之前的sendIntent等方式是有效的补充。通过制作音乐播放器,对安卓开发有了更深的理解。

MusicPlayer

实现音乐播放器进度条界面有很多种方法,下面我介绍一种简单易懂的实现方式: 首先,我们需要一个进度条控件,可以使用Qt中的QProgressBar或者自定义QWidget实现。 然后,在播放器控制部分,我们需要获取当前播放时间和音乐总时长,可以使用QMediaPlayer类中的duration()和position()方法获取。 接下来,我们可以在播放器控制部分定时刷新进度条的值,例如每100ms更新一次,这样就可以实现进度条的动态效果了。 最后,我们可以在进度条上添加一些额外的交互,例如点击进度条可以跳转到指定位置,鼠标悬浮在进度条上可以显示当前播放时间等。 下面是一个简单的例子代码: ```python from PyQt5.QtWidgets import * from PyQt5.QtGui import * from PyQt5.QtCore import * from PyQt5.QtMultimedia import * class MusicPlayer(QWidget): def __init__(self): super().__init__() self.initUI() def initUI(self): # 创建进度条 self.progress_bar = QProgressBar(self) self.progress_bar.setGeometry(10, 10, 280, 30) # 创建播放器 self.media_player = QMediaPlayer(self) # 定时刷新进度条 self.timer = QTimer(self) self.timer.timeout.connect(self.update_progress_bar) self.timer.start(100) # 其他控件和布局 # ... def update_progress_bar(self): duration = self.media_player.duration() / 1000 position = self.media_player.position() / 1000 self.progress_bar.setMaximum(duration) self.progress_bar.setValue(position) # 其他播放器控制方法 # ... if __name__ == '__main__': app = QApplication(sys.argv) player = MusicPlayer() player.show() sys.exit(app.exec_()) ``` 这是一个简单的音乐播放器进度条界面实现,如果需要更多的功能可以根据具体需求进行扩展。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值