简单的音乐播放

public class MusicService extends Service{
    public final IBinder binder = new MyBinder();
    public class MyBinder extends Binder {
        public MusicService getService() {
            return MusicService.this;
        }
    }


    public static int isReturnTo = 0;
    public static MediaPlayer mediaPlayer = new MediaPlayer();
    public static ObjectAnimator animator;
    public MusicService() {
        initMediaPlayer();


    }


    public void initMediaPlayer() {
        try {
            //String file_path = "/storage/0123-4567/K.Will-Melt.mp3";
            String path="http://sc1.111ttt.cn:8282/2018/1/03m/13/396131229550.m4a?tflag=1519095601&pin=6cd414115fdb9a950d827487b16b5f97#.mp3";
//            String file_path = Environment.getExternalStorageDirectory().getAbsolutePath()+"/K.Will-Melt.mp3";
//            //String file_path = "/data/K.Will-Melt.mp3";
//            mediaPlayer.setDataSource(file_path);
            mediaPlayer.setDataSource( path );
            mediaPlayer.prepare();
            mediaPlayer.setLooping(true);  // 设置循环播放
        } catch (Exception e) {
            e.printStackTrace();
        }
    }


    @SuppressLint("WrongConstant")
    public  void AnimatorAction() {
        if (mediaPlayer.isPlaying()) {
            animator.setDuration(5000);
            animator.setInterpolator(new LinearInterpolator()); // 均速旋转
            animator.setRepeatCount( ValueAnimator.INFINITE); // 无限循环
            animator.setRepeatMode(ValueAnimator.INFINITE);
            animator.start();
        }
    }
    private int flag = 0;
    public static String which = "";
    @SuppressLint("WrongConstant")
    @RequiresApi(api = Build.VERSION_CODES.KITKAT)
    public void playOrPause() {
        flag++;
        if (flag >= 1000) flag = 2;


        which = "pause";


        if(mediaPlayer.isPlaying()){
            mediaPlayer.pause();
            animator.pause();
        } else {
            mediaPlayer.start();


            if ((flag == 1) || (isReturnTo == 1)) {
                animator.setDuration(5000);
                animator.setInterpolator(new LinearInterpolator()); // 均速旋转
                animator.setRepeatCount(ValueAnimator.INFINITE); // 无限循环
                animator.setRepeatMode(ValueAnimator.INFINITE);
                animator.start();
            } else {
                animator.resume();
            }
        }
    }
    @RequiresApi(api = Build.VERSION_CODES.KITKAT)
    public void stop() {
        which = "stop";
        animator.pause();
        if(mediaPlayer != null) {
            mediaPlayer.pause();
            mediaPlayer.stop();
            try {
                mediaPlayer.prepare();
                mediaPlayer.seekTo(0);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }




    @Override
    public void onDestroy() {
        mediaPlayer.stop();
        mediaPlayer.release();
        super.onDestroy();
    }
    /**
     * onBind 是 Service 的虚方法,因此我们不得不实现它。
     * 返回 null,表示客服端不能建立到此服务的连接。
     */
    @Override
    public IBinder onBind(Intent intent) {
        return binder;
    }


}

public class MusicActivity extends AppCompatActivity {


    private Button isPlay;
    private Button stop;
    private Button quit;


    private ImageView coverImage;
    // private ObjectAnimator animator;
    private int flag = 0;


    private TextView totalTime;
    private TextView playingTime;
    private TextView stateText;


    private SeekBar seekBar;
    private TextView pathText;


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


        bindServiceConnection();
        musicService = new MusicService();


        coverImage = (ImageView) findViewById(R.id.coverImage);
        musicService.animator = ObjectAnimator.ofFloat(coverImage, "rotation", 0, 359);


        isPlay = (Button) findViewById(R.id.isPlayButton);
        isPlay.setOnClickListener(new myOnClickListener());


        stop = (Button) findViewById(R.id.stopButton);
        stop.setOnClickListener(new myOnClickListener());


        quit = (Button) findViewById(R.id.quitButton);
        quit.setOnClickListener(new myOnClickListener());


        seekBar = (SeekBar) findViewById(R.id.seekBar);
        seekBar.setProgress(musicService.mediaPlayer.getCurrentPosition());
        seekBar.setMax(musicService.mediaPlayer.getDuration());


        totalTime = (TextView) findViewById(R.id.totalTime);
        playingTime = (TextView) findViewById(R.id.playingTime);
        stateText = (TextView) findViewById(R.id.stateText);


        pathText = (TextView) findViewById(R.id.pathText);
//        String sdcard = "音乐文件的路径为:" + Environment.getExternalStorageDirectory().getAbsolutePath().toString()+"/K.Will-Melt.mp3";
//        pathText.setText(sdcard);


    }


    private MusicService musicService;
    private SimpleDateFormat time = new SimpleDateFormat("mm:ss");
    private ServiceConnection sc = new ServiceConnection() {
        @Override
        public void onServiceConnected(ComponentName componentName, IBinder iBinder) {
            musicService = ((MusicService.MyBinder) iBinder).getService();
        }


        @Override
        public void onServiceDisconnected(ComponentName componentName) {
            musicService = null;
        }
    };


    private void bindServiceConnection() {
        Intent intent = new Intent(this, MusicService.class);
        startService(intent);
        bindService(intent, sc, this.BIND_AUTO_CREATE);
    }


    public Handler handler = new Handler();
    public Runnable runnable = new Runnable() {
        @Override
        public void run() {


            isPlay.setOnClickListener(new myOnClickListener());
            stop.setOnClickListener(new myOnClickListener());
            quit.setOnClickListener(new myOnClickListener());


            if(musicService.mediaPlayer.isPlaying()) {
                stateText.setText("Playing");
            } else {
                if (musicService.which.equals("stop"))  {
                    stateText.setText("Stop");
                } else if (musicService.which.equals("pause")){
                    stateText.setText("Pause");
                }
            }
            playingTime.setText(time.format(musicService.mediaPlayer.getCurrentPosition()));
            totalTime.setText(time.format(musicService.mediaPlayer.getDuration()));
            seekBar.setProgress(musicService.mediaPlayer.getCurrentPosition());
            seekBar.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
                @Override
                public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
                    if (fromUser) {
                        musicService.mediaPlayer.seekTo(seekBar.getProgress());
                    }
                }


                @Override
                public void onStartTrackingTouch(SeekBar seekBar) {


                }


                @Override
                public void onStopTrackingTouch(SeekBar seekBar) {


                }
            });
            handler.postDelayed(runnable, 100);
        }
    };


    @Override
    public void onPause(){
        super.onPause();
        if(isApplicationBroughtToBackground()) {
            musicService.isReturnTo = 1;
            Log.e("b","后台中");
        }
    }


    @Override
    public void onRestart() {
        super.onRestart();
        musicService.isReturnTo = 1;
    }


    @Override
    protected void onResume() {


        musicService.AnimatorAction();
        verifyStoragePermissions(this);


        if(musicService.mediaPlayer.isPlaying()) {
            stateText.setText("Playing");
        } else {
            if (musicService.which.equals("stop"))  {
                stateText.setText("Stop");
            } else if (musicService.which.equals("pause")){
                stateText.setText("Pause");
            }
        }
        seekBar.setProgress(musicService.mediaPlayer.getCurrentPosition());
        seekBar.setMax(musicService.mediaPlayer.getDuration());
        handler.post(runnable);
        super.onResume();
        Log.d("hint", "handler post runnable");
    }


    private class myOnClickListener implements View.OnClickListener {
        @RequiresApi(api = Build.VERSION_CODES.KITKAT)
        @Override
        public void onClick(View view) {
            switch (view.getId()) {
                case R.id.isPlayButton:
                    changePlay();
                    musicService.playOrPause();
                    break;
                case R.id.stopButton:
                    musicService.stop();
                    changeStop();
                    break;
                case R.id.quitButton:
                    quit();
                    break;
                default:
                    break;
            }
        }
    }


    private void changePlay() {


        if(musicService.mediaPlayer.isPlaying()){
            stateText.setText("正在播放");
            isPlay.setText("播放");
            //animator.pause();
        } else {
            stateText.setText("Playing");
            isPlay.setText("PAUSE");


        }
    }


    private void changeStop() {
        stateText.setText("Stop");
        seekBar.setProgress(0);
        //animator.pause();
    }


    private void quit() {
        musicService.animator.end();
        handler.removeCallbacks(runnable);
        unbindService(sc);
        try {
            finish();
            System.exit(0);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }


    @Override
    public void onStop() {
        super.onStop();
    }
    @Override
    public void onDestroy() {
        unbindService(sc);
        super.onDestroy();
    }


    //这里是在登录界面label上右上角添加三个点,里面可添加其他功能
    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.settings, menu);
        return true;
    }


    private void getOverflowMenu() {
        try {
            ViewConfiguration config = ViewConfiguration.get(this);
            Field menuKeyField = ViewConfiguration.class.getDeclaredField("sHasPermanentMenuKey");
            if (menuKeyField != null) {
                menuKeyField.setAccessible(true);
                menuKeyField.setBoolean(config, false);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }


    private boolean isApplicationBroughtToBackground() {
        ActivityManager am = (ActivityManager) getSystemService( Context.ACTIVITY_SERVICE);
        List<ActivityManager.RunningTaskInfo> tasks = am.getRunningTasks(1);
        if (!tasks.isEmpty()) {
            ComponentName topActivity = tasks.get(0).topActivity;
            if (!topActivity.getPackageName().equals(getPackageName())) {
                return true;
            }
        }
        return false;
    }


    // Storage Permissions
    private static final int REQUEST_EXTERNAL_STORAGE = 1;
    private static String[] PERMISSIONS_STORAGE = {
            Manifest.permission.READ_EXTERNAL_STORAGE,
            Manifest.permission.WRITE_EXTERNAL_STORAGE
    };


    /**
     * Checks if the app has permission to write to device storage
     *
     * If the app does not has permission then the user will be prompted to grant permissions
     *
     * @param activity
     */
    public static void verifyStoragePermissions(Activity activity) {
        // Check if we have write permission
        int permission = ActivityCompat.checkSelfPermission(activity, Manifest.permission.WRITE_EXTERNAL_STORAGE);


        if (permission != PackageManager.PERMISSION_GRANTED) {
            // We don't have permission so prompt the user
            ActivityCompat.requestPermissions(
                    activity,
                    PERMISSIONS_STORAGE,
                    REQUEST_EXTERNAL_STORAGE
            );
        }
    }
}

在res创建menu文件夹

settings.xml

<menu xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto">
    <item
        android:id="@+id/action_settings"
        android:orderInCategory="100"
        app:showAsAction="never"
        android:title="settings"/>

</menu>

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:id="@+id/relatives">




    <ImageView
        android:id="@+id/coverImage"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginTop="20dp"
        android:src="@mipmap/acm"
        android:scaleType="centerInside"
        android:layout_centerHorizontal="true"/>


    <TextView
        android:id="@+id/stateText"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_below="@+id/coverImage"
        android:padding="15dp"
        android:text="空转"
        android:textSize="20dp"/>


    <TableRow
        android:id="@+id/row1"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_below="@+id/stateText"
        android:padding="15dp">
        <TextView
            android:id="@+id/playingTime"
            android:layout_weight="1"
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:text="00:00"
            android:textSize="20dp"/>


        <SeekBar
            android:id="@+id/seekBar"
            android:layout_weight="4"
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:layout_gravity="center_vertical"/>


        <TextView
            android:id="@+id/totalTime"
            android:layout_weight="1"
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:text="00:00"
            android:textSize="20dp"/>
    </TableRow>


    <TableRow
        android:id="@+id/row2"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_below="@+id/row1"
        android:gravity="center_horizontal"
        android:padding="15dp">
        <Button
            android:id="@+id/isPlayButton"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:textSize="22dp"
            android:text="播放"
            />
 
        <Button
            android:id="@+id/stopButton"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:textSize="22dp"
            android:text="暂停"
            android:layout_marginLeft="15dp"
            android:layout_marginRight="15dp"/>


        <Button
            android:id="@+id/quitButton"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:textSize="22dp"
            android:text="返回上一个页面" />
    </TableRow>


    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_below="@+id/row2"
        android:layout_centerHorizontal="true"
        android:textSize="18dp"
        android:id="@+id/pathText"/>
</RelativeLayout>


  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值