1.需要提前准备的图标

2.往虚拟机里面导入歌曲

3.写布局文件

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity"
    android:orientation="vertical">

    <TextView
        android:id="@+id/showMessage"
        android:layout_width="match_parent"
        android:layout_height="300dp"
        android:layout_alignParentLeft="true"
        android:layout_alignParentTop="true"
        android:layout_marginTop="69dp"
        android:gravity="center"
        android:text="播放信息"
        android:textColor="#000000"
        android:textSize="35sp" />

    <TextView
        android:id="@+id/allTime"
        android:layout_width="match_parent"
        android:layout_height="200dp"
        android:layout_above="@+id/stop"
        android:layout_alignLeft="@+id/stop"
        android:layout_marginBottom="22dp"
        android:text="歌词占个地方"
        android:textColor="#000000"/>
    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="76dp"
        android:layout_marginBottom="100dp"
        android:orientation="horizontal">

        <ImageButton
            android:id="@+id/lastsong"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:scaleType="centerInside"
            android:background="#FFFFFF"
            android:src="@drawable/last" />

        <ImageButton
            android:id="@+id/playsong"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:scaleType="centerInside"
            android:background="#FFFFFF"
            android:src="@drawable/play" />

        <ImageButton
            android:id="@+id/pause"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:scaleType="centerInside"
            android:background="#FFFFFF"
            android:src="@drawable/pause" />

        <ImageButton
            android:id="@+id/stop"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:scaleType="centerInside"
            android:background="#FFFFFF"
            android:src="@drawable/stop" />
        <ImageButton
            android:id="@+id/nextsong"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:scaleType="centerInside"
            android:background="#FFFFFF"
            android:src="@drawable/next" />

    </LinearLayout>
</LinearLayout>

 4.主活动

package com.example.musicplayer;

import androidx.appcompat.app.AppCompatActivity;

import android.media.MediaPlayer;
import android.os.Bundle;
import android.os.Environment;
import android.view.View;
import android.view.WindowManager;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

public class MainActivity extends AppCompatActivity {
    private MediaPlayer player;//播放器
    private int stateCode = 2;//0.播放 1.暂停 2.停止
    private File file; //文件对象用于音频加载
    List<String> songList = new ArrayList<String>();
    int index = 0;//播放歌曲序号-1
    TextView showMessage;
    ImageView btn_play,btn_stop,btn_pause,btn_next,btn_last;

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

        getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,WindowManager.LayoutParams.FLAG_FULLSCREEN);

        btn_play = findViewById(R.id.playsong);
        btn_stop = findViewById(R.id.stop);
        btn_pause = findViewById(R.id.pause);
        btn_next = findViewById(R.id.nextsong);
        btn_last = findViewById(R.id.lastsong);
        showMessage = findViewById(R.id.showMessage);

        if(!isFileExists())
            btn_play.setEnabled(false);
        //播放完成时间监听器
        player.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
            @Override
            public void onCompletion(MediaPlayer mp) {
                playSong(2,"下一首");
            }
        });
        //播放按钮
        btn_play.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View arg0) {
                play();
                stateCode = 0;
                setBtnAndMessage("play","正在播放",false,true,true);
            }
        });
        //暂停
        btn_pause.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                player.pause();
                stateCode = 1;
                setBtnAndMessage("已暂停播放","暂停播放",true,false,true);
            }
        });
        //停止
        btn_stop.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View arg0) {
                player.stop();
                stateCode = 2;
                setBtnAndMessage("停止播放","将播放",true,false,false);
            }
        });
        //下一曲
        btn_next.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View arg0) {
                playSong(2,"下一首");
            }
        });
        //上一曲
        btn_last.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View arg0) {
                playSong(1,"上一首");
            }
        });
    }

    //消息及提醒
    public void setBtnAndMessage(String message,String text,boolean play,boolean pause,boolean stop){
        setTextMessage(message, text);
        btn_play.setEnabled(play);
        btn_pause.setEnabled(pause);
        btn_stop.setEnabled(stop);
    }

    //消息及提示
    public void setTextMessage(String text,String playState){
        Toast.makeText(getApplicationContext(), text, Toast.LENGTH_SHORT).show();
        showMessage.setText(playState+"\n"+songList.get(index));
    }

    //flag 2:last 1:next
    public void playSong(int flag,String text){
        stateCode = 0;
        if(flag == 1){//若为最后一首,播放下一首,索引置0
            if( index == (songList.size()-1))
                index = 0;
            else
                index++;
        }else if(flag == 2){//若为第一首,播放上一首,索引置为(总长 -1)
            if(index == 0)
                index = songList.size()-1;
            else
                index--;
        }
        loadMusic();
        readyToPlay();
        setBtnAndMessage(text,"正在播放",false,true,true);
    }

    //app启动时加载音频
    public boolean isFileExists(){
        String state = Environment.getExternalStorageState();
        if(state.equals(Environment.MEDIA_MOUNTED)){
            songList = getFilesAllName();//加载sdcard目录下所有mp3音乐到播放列表
            loadMusic();//加载当前index指向音乐
            if(file.exists()){
                player = new MediaPlayer();
                try {
                    player.setDataSource(file.getAbsolutePath());//获取文件绝对路径加载音乐
                    player.prepare();
                    setBtnAndMessage("音乐已加载,请点击播放", "点击播放", true, false, false);
                } catch (Exception e) {
                    e.printStackTrace();
                }
                return true;
            }else
                return false;
        }else
            Toast.makeText(MainActivity.this, "SD卡故障", Toast.LENGTH_SHORT).show();
        return false;
    }

    //播放
    public void play(){///第一次歌曲预加载,只需播放
        if(stateCode == 1){
            player.start();
            setTextMessage("开始播放", "正在播放");
        }else if(stateCode == 2){
            loadMusic();
            readyToPlay();
            setTextMessage("开始播放", "正在播放");
        }
    }

    //预备到播放
    public void readyToPlay(){
        try {
            player.reset();// 从新设置要播放的音乐
            player.setDataSource(file.getAbsolutePath());//加载音乐
            player.prepare();
            player.start();// 播放音乐
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    //清理资源
    @Override
    protected void onDestroy() {
        if(player.isPlaying())
            player.stop();
        player.release();
        super.onDestroy();
    }
    public void loadMusic(){
        file = new File(Environment.getExternalStorageDirectory()+File.separator + songList.get(index));
    }
    //获取SD卡所有的.mp3资源
    public List<String> getFilesAllName(){
        File file = new File(Environment.getExternalStorageDirectory()+File.separator);
        File[] files = file.listFiles();
        List<String> s = new ArrayList<String>();
        for(int i =0;i<files.length;i++){
            if(files[i].toString().endsWith(".mp3"))
                s.add(files[i].getName());
        }
        return s;
    }
}

 5.清单文件给权限

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.example.musicplayer">
    <uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/>

    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:roundIcon="@mipmap/ic_launcher_round"
        android:supportsRtl="true"
        android:theme="@style/Theme.Map">
        <activity
            android:name=".MainActivity"
            android:exported="true">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>

</manifest>

6.运行应用,在虚拟机设备的应用里面给应用权限

找到你写的应用

给权限

 

 

7.启动应用,播放吧

 

环境:Android-studio

Android6 

Logo

华为开发者空间,是为全球开发者打造的专属开发空间,汇聚了华为优质开发资源及工具,致力于让每一位开发者拥有一台云主机,基于华为根生态开发、创新。

更多推荐