• 播放音乐


    MediaPlayer常见用法

    关键代码:

    public class MainActivity extends Activity {
    
        private Button play,pause,stop;
        private MediaPlayer mediaPlayer = new MediaPlayer();
    
        @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_main);
            initMusic();
        }
    
    
        private void initMusic(){
            try{
                File file = new File(Environment.getExternalStorageDirectory()+"/Guo","a.mp3");
                mediaPlayer.setDataSource(file.getPath());
                mediaPlayer.prepare();
            }catch (Exception e){
                e.printStackTrace();
            }
        }
    
        protected void myClick(View v){
            if( v.getId() == R.id.play ){
                if( !mediaPlayer.isPlaying() ){
                    mediaPlayer.start(); //开始播放
                }
            }
    
            if( v.getId() == R.id.pause ){
                if( mediaPlayer.isPlaying() ){
                    mediaPlayer.pause(); // 暂停
                }
            }
    
            if( v.getId() == R.id.stop ){
                if( mediaPlayer.isPlaying() ){
                    mediaPlayer.reset(); // 停止播放
                    initMusic();
                }
            }
        }
    
        @Override
        protected void onDestroy() {
            super.onDestroy();
            if( mediaPlayer != null  ){
                mediaPlayer.stop();
                mediaPlayer.release();
            }
        }
    }

    所需权限:

    <uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/>
  • 相关阅读:
    Ubuntu 14.04 LTS 安装 NVIDIA 显卡驱动后的屏幕亮度调节问题
    算法算法算法
    Java transient关键字
    使用git和github管理自己的项目---基础操作学习[转]
    Linux 查看系统硬件信息[转]
    实现Servlet容器一
    nginx入门三
    nginx入门二
    nginx入门一
    centos7入门
  • 原文地址:https://www.cnblogs.com/itfenqing/p/6747263.html
Copyright © 2020-2023  润新知