音乐播放器与RadioButton

前几天有人向我要音乐播放器源代码 而自己因为系统问题而丢失了 所以决定重写一遍

 

为了与以前不同 所以今天打算不用ListView 而用RadioGroup 其实是换汤不换药而已

 

 

 

 

[代码 步骤]

1. 定制化有RadioGroup的界面:main.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    >
<LinearLayout 
    android:orientation="horizontal"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    >
<Button
	android:id="@+id/cmd"  
    android:layout_width="wrap_content" 
    android:layout_height="500dip" 
    android:text="Loading.." 
/>
</LinearLayout>
<RadioGroup  
	android:id="@+id/rgroup"
	android:orientation="vertical"  
    android:layout_width="fill_parent" 
    android:layout_height="wrap_content" 
    />
</LinearLayout>

 

 

2. 初始化所有View

public void initialView(){
    	rGroup = (RadioGroup) findViewById(R.id.rgroup);
    	cmd = (Button) findViewById(R.id.cmd);
    }

 

3. 检索MediaStore 得到sdcard所以音乐的Uri

Cursor c = getContentResolver().query(
                MediaStore.Audio.Media.EXTERNAL_CONTENT_URI, 
                null, null, null, null);  
        

 

4. 把上面的音乐文件装入RadioButton

public void loadMusic(Cursor c){
    	int index = c.getColumnIndex(MediaStore.Audio.AudioColumns.TITLE);
    	
    	int i=BASE_ID;
    	for(c.moveToFirst();!c.isAfterLast();c.moveToNext()){
    		String title = c.getString(index);
    		
    		RadioButton rb = new RadioButton(this);
    		rb.setText(title);
    		rb.setId(i++);
    		
    		rGroup.addView(rb);
    	}
    }

 

5. 设立RadioGroup的选择监听器 并播放选中目标

rGroup.setOnCheckedChangeListener(new OnCheckedChangeListener(){
			@Override
			public void onCheckedChanged(RadioGroup group, int checkedId) {
				// TODO Auto-generated method stub
				int id = group.getCheckedRadioButtonId()-BASE_ID+1;
				
				try {
					playMusic(id);
				} catch (IllegalArgumentException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				} catch (IllegalStateException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				} catch (IOException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
        	
        });



 

public void playMusic(long arg3) throws IllegalArgumentException, IllegalStateException, IOException{
    	Uri uri = Uri.withAppendedPath(
                MediaStore.Audio.Media.EXTERNAL_CONTENT_URI, 
                String.valueOf(arg3));
    	
    	mPlayer.release();
    	mPlayer = MediaPlayer.create(this, uri);
    	mPlayer.start();
    }

 

 

 5. emulator 运行截图:

 

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值