溫馨提示×

溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊×
其他方式登錄
點(diǎn)擊 登錄注冊 即表示同意《億速云用戶服務(wù)條款》

如何在Android中實(shí)現(xiàn)一個(gè)音樂播放器

發(fā)布時(shí)間:2021-05-13 16:18:35 來源:億速云 閱讀:195 作者:Leah 欄目:開發(fā)技術(shù)

如何在Android中實(shí)現(xiàn)一個(gè)音樂播放器?很多新手對此不是很清楚,為了幫助大家解決這個(gè)難題,下面小編將為大家詳細(xì)講解,有這方面需求的人可以來學(xué)習(xí)下,希望你能有所收獲。

實(shí)現(xiàn)過程

導(dǎo)入項(xiàng)目所需的音樂文件、圖標(biāo)、背景等

1.創(chuàng)建一個(gè)raw文件夾,將音樂文件導(dǎo)入到這個(gè)文件夾中,方便我們在項(xiàng)目中使用

2.在drawable中導(dǎo)入所需的圖片、圖標(biāo)

設(shè)計(jì)UI界面

1.設(shè)計(jì)5個(gè)button控件,分別對應(yīng)上一曲,下一曲,暫停,播放,退出

2.設(shè)計(jì)3個(gè)TextView,分別對應(yīng)歌曲的介紹信息、歌曲的進(jìn)度(歌曲的總時(shí)間和歌曲當(dāng)前播放的時(shí)間)、歌曲的名字

service服務(wù)的編寫
創(chuàng)建一個(gè)MusicService對象繼承Service

MusicService所需要的成員變量

MyReceiver serviceReceiver;
Thread processThread;
AssetManager am;//是附件管理器,用于根據(jù)文件名找到文件所在并打開文件
String[] musics = new String[]{"legendsneverdie.mp3", "promise.mp3",
        "beautiful.mp3"};//默認(rèn)顯示的歌曲信息
MediaPlayer mPlayer;
// 當(dāng)前的狀態(tài),0x11代表沒有播放;0x12代表正在播放;0x13代表暫停
int status = 0x11;
// 記錄當(dāng)前正在播放的音樂
int current = 0;

實(shí)現(xiàn)循環(huán)播放

public void onCreate() {
        super.onCreate();
        am = getAssets();

        // 創(chuàng)建BroadcastReceiver
        serviceReceiver = new MyReceiver();
        // 創(chuàng)建IntentFilter
        IntentFilter filter = new IntentFilter();
        filter.addAction(MainActivity.CTL_ACTION);
        registerReceiver(serviceReceiver, filter);


        // 創(chuàng)建MediaPlayer
        mPlayer = new MediaPlayer();
        // 為MediaPlayer播放完成事件綁定監(jiān)聽器
        mPlayer.setOnCompletionListener(new OnCompletionListener()
        {
            @Override
            public void onCompletion(MediaPlayer mp) {
                Log.d("musicService", "播放完成");
                current++;
                if (current >= 3) {
                    current = 0;
                }
                // 準(zhǔn)備并播放音樂
                prepareAndPlay(musics[current]);
                //發(fā)送廣播通知Activity更改文本框
                Intent sendIntent = new Intent(MainActivity.UPDATE_ACTION);
                sendIntent.putExtra("current", current);
                sendIntent.putExtra("currentTime", mPlayer.getCurrentPosition());
                sendIntent.putExtra("totalTime", mPlayer.getDuration());
                // 發(fā)送廣播,將被Activity組件中的BroadcastReceiver接收到
                sendBroadcast(sendIntent);

            }
        });
    private void prepareAndPlay(String music) {
        try {
            // 打開指定音樂文件
            AssetFileDescriptor afd = am.openFd(music);
            mPlayer.reset();
            // 使用MediaPlayer加載指定的聲音文件。
            mPlayer.setDataSource(afd.getFileDescriptor(),
                    afd.getStartOffset(), afd.getLength());
            // 準(zhǔn)備聲音
            mPlayer.prepare();
            // 播放
            mPlayer.start();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

實(shí)現(xiàn)刷新進(jìn)度條

processThread = new Thread(new Runnable() {
        @Override
        public void run() {
            while (true) {
                if (status == 0x12) {
                    try {
                        Thread.sleep(1000);
                        Intent sendIntent = new Intent(MainActivity.UPDATE_ACTION);
                        sendIntent.putExtra("current", current);
                        sendIntent.putExtra("currentTime", mPlayer.getCurrentPosition());
                        sendIntent.putExtra("totalTime", mPlayer.getDuration());
                        // 發(fā)送廣播,將被Activity組件中的BroadcastReceiver接收到
                        sendBroadcast(sendIntent);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
            }
        }
    });
    processThread.start();
}

廣播通信接收器的實(shí)現(xiàn)(用于實(shí)現(xiàn)和activity的通信)

public class MyReceiver extends BroadcastReceiver {
    @Override
    public void onReceive(final Context context, Intent intent) {
        int control = intent.getIntExtra("control", -1);
        Log.d("musicReceiver", "收到廣播, control=" + control);
        switch (control) {
            // 播放或暫停
            case 1:
                // 原來處于沒有播放狀態(tài)
                if (status == 0x11) {
                    // 準(zhǔn)備并播放音樂
                    prepareAndPlay(musics[current]);
                    status = 0x12;
                }
                // 原來處于播放狀態(tài)
                else if (status == 0x12) {
                    // 暫停
                    mPlayer.pause();
                    // 改變?yōu)闀和顟B(tài)
                    status = 0x13;
                }
                // 原來處于暫停狀態(tài)
                else if (status == 0x13) {
                    // 播放
                    mPlayer.start();
                    // 改變狀態(tài)
                    status = 0x12;
                }
                break;
                // 下一首
            case 2:
                if (status == 0x12 || status == 0x13) {
                    mPlayer.stop();
                    if (current + 1 >= musics.length) {
                        current = 0;
                    } else {
                        current++;
                    }
                    prepareAndPlay(musics[current]);
                    status = 0x12;
                    break;
                }
                // 上一首
            case 3:
                if (status == 0x12 || status == 0x13) {
                    mPlayer.stop();
                    if (current - 1 < 0) {
                        current = musics.length - 1;
                    } else {
                        current--;
                    }
                    prepareAndPlay(musics[current]);
                    status = 0x12;
                }

        }

        // 廣播通知Activity更改圖標(biāo)、文本框
        Intent sendIntent = new Intent(MainActivity.UPDATE_ACTION);
        sendIntent.putExtra("update", status);
        sendIntent.putExtra("current", current);
        // 發(fā)送廣播,將被Activity組件中的BroadcastReceiver接收到
        sendBroadcast(sendIntent);
    }
}

activity的實(shí)現(xiàn)

初始化和動態(tài)綁定接收器

// 獲取界面中顯示歌曲標(biāo)題、作者文本框
TextView title, author, currentTime, totalTime;
// 播放/暫停、停止按鈕
ImageButton play;
ImageView lastMusic, nextMusic;
// 進(jìn)度條
ProgressBar progressBar;

ActivityReceiver activityReceiver;

public static final String CTL_ACTION =
        "org.xr.action.CTL_ACTION";
public static final String UPDATE_ACTION =
        "org.xr.action.UPDATE_ACTION";
// 定義音樂的播放狀態(tài),0x11代表沒有播放;0x12代表正在播放;0x13代表暫停
int status = 0x11;
String[] titleStrs = new String[]{"Legends Never Die", "約定", "美麗新世界"};
String[] authorStrs = new String[]{"英雄聯(lián)盟", "周蕙", "伍佰"};

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);

    // 獲取程序界面界面中的兩個(gè)按鈕
    play = (ImageButton) this.findViewById(R.id.play);
    lastMusic = this.findViewById(R.id.lastMusic);
    nextMusic = this.findViewById(R.id.nextMusic);
    title = (TextView) findViewById(R.id.title);
    author = (TextView) findViewById(R.id.author);
    currentTime = findViewById(R.id.currentTime);
    totalTime = findViewById(R.id.totalTime);
    progressBar = findViewById(R.id.progressBar);


    // 為兩個(gè)按鈕的單擊事件添加監(jiān)聽器
    play.setOnClickListener(this);
    lastMusic.setOnClickListener(this);
    nextMusic.setOnClickListener(this);

    activityReceiver = new ActivityReceiver();
    // 創(chuàng)建IntentFilter
    IntentFilter filter = new IntentFilter();
    // 指定BroadcastReceiver監(jiān)聽的Action
    filter.addAction(UPDATE_ACTION);
    // 注冊BroadcastReceiver
    registerReceiver(activityReceiver, filter);

    Intent intent = new Intent(this, MusicService.class);
    // 啟動后臺Service
    startService(intent);
}

設(shè)置activity的廣播接收器(接收service發(fā)送過來的廣播)

public void onReceive(Context context, Intent intent) {
    // 獲取Intent中的update消息,update代表播放狀態(tài)
    int update = intent.getIntExtra("update", -1);
    // 獲取Intent中的current消息,current代表當(dāng)前正在播放的歌曲
    int current = intent.getIntExtra("current", -1);
    int totalPosition = intent.getIntExtra("totalTime", -1);
    int currentPosition = intent.getIntExtra("currentTime", -1);
    Log.d("activityReceiver", "收到廣播");
    Log.d("activityReceiver", "current:" + current + " totalPosition:" + totalPosition + " currentPosition:" + currentPosition + " update:" + update);
    if (current >= 0) {
        title.setText(titleStrs[current]);
        author.setText(authorStrs[current]);
    }

    if (totalPosition >= 0) {
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("mm:ss", Locale.CHINA);
        Date date = new Date(totalPosition);
        String formatTime = simpleDateFormat.format(date);
        totalTime.setText(formatTime);
    }

    if (currentPosition >= 0) {
        double process = ((double)currentPosition / totalPosition)*100;
        Log.d("activityReceiver", "當(dāng)前進(jìn)度:" + (double)currentPosition/totalPosition);
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("mm:ss", Locale.CHINA);
        Date date = new Date(currentPosition);
        String formatTime = simpleDateFormat.format(date);
        progressBar.setProgress((int) process);
        currentTime.setText(formatTime);
    }

    switch (update) {
        case 0x11:
            play.setImageResource(R.drawable.play);
            status = 0x11;
            break;
        // 控制系統(tǒng)進(jìn)入播放狀態(tài)
        case 0x12:
            // 播放狀態(tài)下設(shè)置使用暫停圖標(biāo)
            play.setImageResource(R.drawable.pause);
            // 設(shè)置當(dāng)前狀態(tài)
            status = 0x12;
            break;
        // 控制系統(tǒng)進(jìn)入暫停狀態(tài)
        case 0x13:
            // 暫停狀態(tài)下設(shè)置使用播放圖標(biāo)
            play.setImageResource(R.drawable.play);
            // 設(shè)置當(dāng)前狀態(tài)
            status = 0x13;
            break;
    }
}

實(shí)現(xiàn)圖標(biāo)的點(diǎn)擊功能

// 創(chuàng)建Intent
    Intent intent = new Intent("org.xr.action.CTL_ACTION");
    switch (source.getId()) {
        // 按下播放/暫停按鈕
        case R.id.play:
            intent.putExtra("control", 1);
            break;
        case R.id.lastMusic:
            intent.putExtra("control", 3);
        case R.id.nextMusic:
            intent.putExtra("control", 2);
    }
    // 發(fā)送廣播,將被Service組件中的BroadcastReceiver接收到
    sendBroadcast(intent);
}

Android是什么

Android是一種基于Linux內(nèi)核的自由及開放源代碼的操作系統(tǒng),主要使用于移動設(shè)備,如智能手機(jī)和平板電腦,由美國Google公司和開放手機(jī)聯(lián)盟領(lǐng)導(dǎo)及開發(fā)。

看完上述內(nèi)容是否對您有幫助呢?如果還想對相關(guān)知識有進(jìn)一步的了解或閱讀更多相關(guān)文章,請關(guān)注億速云行業(yè)資訊頻道,感謝您對億速云的支持。

向AI問一下細(xì)節(jié)

免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場,如果涉及侵權(quán)請聯(lián)系站長郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。

AI