音乐播放上一首,下一首

添加权限:

SD卡读写权限

MainActivity:

public class MainActivity extends AppCompatActivity {

    private int index=0;
    private List musiclist;
    private MediaPlayer mediaPlayer;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        musiclist = Arrays.asList("/sdcard/a.mp3","/sdcard/a.mp3");
        findViewById(R.id.bofang).setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                // TODO Auto-generated method stub
                bofang(index);
            }
        });
        findViewById(R.id.shang).setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                if (mediaPlayer!=null&&mediaPlayer.isPlaying()) {
                    if (index<=0) {
                        Toast.makeText(MainActivity.this, "已经是第一首音乐了",Toast.LENGTH_LONG).show();
                    }else {
                        --index;
                        tingzhi();
                        bofang(index);
                    }
                }
            }
        });
        findViewById(R.id.xia).setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                if (mediaPlayer!=null&&mediaPlayer.isPlaying()) {
                    if (index<(musiclist.size()-1)) {
                        ++index;
                        tingzhi();
                        bofang(index);
                    }else {
                        Toast.makeText(MainActivity.this, "已经是最后一首音乐了", Toast.LENGTH_SHORT).show();
                    }
                }
            }
        });
    }
    public void bofang(int index){
        mediaPlayer = new MediaPlayer();
        mediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
        try {
            mediaPlayer.setDataSource(musiclist.get(index));
            mediaPlayer.prepare();
            mediaPlayer.start();
        } catch (Exception e) {

        }

    }
    public void tingzhi(){
        if (mediaPlayer!=null&&mediaPlayer.isPlaying()) {
            mediaPlayer.stop();
            mediaPlayer.release();
            mediaPlayer=null;
        }
    }
}


你可能感兴趣的:(安卓移动互联)