基于Android的简易音乐盒设计

基于Android的简易音乐盒设计

最近需要完成一个Android大作业,太难的app自己做不出来,太简单的提不起任何兴趣,我就把这学期学习过的课本翻了几遍,找到几个例子,把他们结合起来,完成一个简易的音乐播放器的设计。作为初学者,很高兴通过自己两天的努力,做了一个自己比较满意的小软件出来。

功能不太多,它具备:音乐播放器的开始,停止,上一曲,下一曲,音量的加减以及通过重力控制切换歌曲的效果(可通过甩动手机来切换歌曲),同时还具备图片切换和震动效果。

通过这两天的学习和设计,我对Android和java的学习方法有更加鲜明的认识,在测试的过程中,我不断地在成功和失败中徘徊,真正理解了失败是成功之母的含义,每当我想要放弃的时候,脑海里就会浮出爱迪生失败几百次的时候,顿时就会坚持下去了!万事开头难,这是我的第一篇 博客,但这不会是最后一篇。

MainActivity.java

import android.app.Service;
import android.hardware.Sensor;
import android.hardware.SensorEvent;
import android.hardware.SensorEventListener;
import android.hardware.SensorManager;
import android.media.AudioManager;
import android.media.MediaPlayer;
import android.os.Bundle;
import android.os.Vibrator;
import android.support.v7.app.ActionBarActivity;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.CheckBox;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
public class MainActivity extends ActionBarActivity implements SensorEventListener {
	TextView txt;
	ImageButton mStopButton,mStartButton,mPauseButton,mNextButton,mPreviousButton,mIncreaseButton,mDecreaseButton;
	MediaPlayer mMediaPlayer;
	CheckBox ch1,ch2,ch3;
	private AudioManager audioManager;
	int[] res_file = new int[]{R.raw.music1,R.raw.music2,R.raw.music3,R.raw.music4};
	String[] name = new String[]{"乐器","水流","冒泡","激昂"};
	int count,counta = 0;
	int index = 0;
	int maxVolume,currentVolume;
	int UPTATE_INTERVAL_TIME =700;
	long lastUpdateTime=0;//上次检测时间
	long currentTime1,currentTime2=10,currentTime3=10;
	private SensorManager mSensorManager;
	private Vibrator vibrator;
	ImageView img;
	//存放图片ID的int数组
	int[] imgs = {
			R.drawable.img1,
			R.drawable.img2,
			R.drawable.img3,
			R.drawable.img4,				
	};
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);
	
		/* 构建MediaPlayer对象 */
		mMediaPlayer = new MediaPlayer();
		/* 构建AudioManager对象 */
		audioManager = (AudioManager) getSystemService(Service.AUDIO_SERVICE);
		/*关联TextView组件*/
		txt = (TextView)findViewById(R.id.text1);
		/*关联停止、开始、暂停、下一曲、上一曲、增大音量、减小音量按钮*/
		mStopButton = (ImageButton) findViewById(R.id.stop);
		mStartButton = (ImageButton) findViewById(R.id.Start);
		mPauseButton = (ImageButton) findViewById(R.id.Pause);
		mNextButton= (ImageButton) findViewById(R.id.next);
		mPreviousButton= (ImageButton) findViewById(R.id.previous);
		mIncreaseButton= (ImageButton) findViewById(R.id.increase);
		mDecreaseButton= (ImageButton) findViewById(R.id.decrease);
		/*关联复选键*/
		ch1=(CheckBox)findViewById(R.id.ch1);
		ch2=(CheckBox)findViewById(R.id.ch2);
		ch3=(CheckBox)findViewById(R.id.ch3);
		/*关联ImageView组件*/
		img=(ImageView)findViewById(R.id.img);
		/*添加组件的监听事件*/
		mNextButton.setOnClickListener(new mNextClick());
		mPreviousButton.setOnClickListener(new mPreviousClick());
		mIncreaseButton.setOnClickListener(new mIncreaseClick());
		mDecreaseButton.setOnClickListener(new mDecreaseClick());
		mStopButton.setOnClickListener(new mStopClick());
		mStartButton.setOnClickListener(new mStartClick());
		mPauseButton.setOnClickListener(new mPauseClick());
		/*获取传感器管理服务*/
		mSensorManager=(SensorManager)getSystemService(SENSOR_SERVICE);
		/*获取震动对象*/
		vibrator = (Vibrator)getApplication().getSystemService(Service.VIBRATOR_SERVICE);
	}
    /*停止按钮事件*/
	class mStopClick implements OnClickListener{
		@Override
		public void onClick(View v) {
			// TODO Auto-generated method stub
			/*是否播放*/
			if(mMediaPlayer.isPlaying()){
				//重置MediaPlayer
				mMediaPlayer.reset();
				mMediaPlayer.release();//释放占用的资源
				Toast.makeText(MainActivity.this,"已停止,重复按下会退出",Toast.LENGTH_SHORT).show();
			}else{
				mMediaPlayer.release();};
		}		
	}
	/*播放按钮事件*/
	class mStartClick implements OnClickListener{
		@Override
		public void onClick(View v) {
			// TODO Auto-generated method stub
				try{
					mMediaPlayer = MediaPlayer.create(MainActivity.this,res_file[count]);
					mMediaPlayer.start();					
				} catch(Exception e) { }
				int a = count+1;
				Toast.makeText(MainActivity.this,"歌曲"+a+":"+name[counta],Toast.LENGTH_SHORT).show();
		}		
	}
	/*暂停按钮事件*/
	class mPauseClick implements OnClickListener{
		@Override
		public void onClick(View v) {
			// TODO Auto-generated method stub
			if (mMediaPlayer.isPlaying()){
				/*暂停*/
				mMediaPlayer.pause();
				Toast.makeText(MainActivity.this,"暂停:"+name[counta],Toast.LENGTH_SHORT).show();
			}
			else
			{
				/*开始播放*/
				mMediaPlayer.start();
				Toast.makeText(MainActivity.this,"播放:"+name[counta],Toast.LENGTH_SHORT).show();
			}
		}
	}
	/*下一首按钮事件*/
	class mNextClick implements OnClickListener{
	@Override
	public void onClick(View arg0) {
		// TODO Auto-generated method stub
		count++;
		counta++;
		index=count;
	    if (count == res_file.length){
	    	count = 0;
	    	counta=0;
	    	index=0;
	    }
	    try{
	    	mMediaPlayer.reset(); //重置
			mMediaPlayer = MediaPlayer.create(MainActivity.this,res_file[count]);//获取资源文件,准备
			mMediaPlayer.start();	//开始				
		} catch(Exception e) { }
	    int a = count +1;
	    Toast.makeText(MainActivity.this,"歌曲"+a+":"+name[counta],Toast.LENGTH_SHORT).show();
	    img.setImageResource(imgs[index]);//图片跟随跳切换
		}   
	}
	/*上一首按钮事件*/
	class mPreviousClick implements OnClickListener{
		
		@Override
		public void onClick(View arg0) {
			// TODO Auto-generated method stub
			count--;
			counta--;
			index=count;
		    if (count == -1){
		    	count = res_file.length-1;
		    	counta = name.length-1;
		    	index=count;
		    }
		    try{
		    	mMediaPlayer.reset();
				mMediaPlayer = MediaPlayer.create(MainActivity.this,res_file[count]);
				mMediaPlayer.start();					
			} catch(Exception e) { }
		    int a = count +1;
		    Toast.makeText(MainActivity.this,"歌曲"+a+":"+name[counta],Toast.LENGTH_SHORT).show();
		    img.setImageResource(imgs[index]);
		}
		
	}
	/*增大音量按钮事件*/
	class mIncreaseClick implements OnClickListener{

		@Override
		public void onClick(View arg0) {
			// TODO Auto-generated method stub
			maxVolume = audioManager.getStreamMaxVolume(AudioManager.STREAM_MUSIC);//最大音量
			/*Adjust增加音量*/
            audioManager.adjustStreamVolume(AudioManager.STREAM_MUSIC,AudioManager.ADJUST_RAISE,AudioManager.FLAG_SHOW_UI);
            currentVolume = audioManager.getStreamVolume(AudioManager.STREAM_MUSIC);//当前音量
            Toast.makeText(MainActivity.this,"音量增加,最大音量是:" + maxVolume + ",当前音量" + currentVolume,
                    Toast.LENGTH_SHORT).show();
		}
		
	}
	/*减小音量按钮事件*/
	class mDecreaseClick implements OnClickListener{

		@Override
		public void onClick(View arg0) {
			// TODO Auto-generated method stub
			maxVolume = audioManager.getStreamMaxVolume(AudioManager.STREAM_MUSIC);
			/*Adjust减小音量*/
            audioManager.adjustStreamVolume(AudioManager.STREAM_MUSIC,AudioManager.ADJUST_LOWER,AudioManager.FLAG_SHOW_UI);
            currentVolume = audioManager.getStreamVolume(AudioManager.STREAM_MUSIC);
            Toast.makeText(MainActivity.this,"音量减小,最大音量是:" + maxVolume + ",当前音量" + currentVolume,
                    Toast.LENGTH_SHORT).show();
		}		
	}
	/*注册加速度传感器事件*/
	@Override
	protected void onResume()
	{
		super.onResume();
		mSensorManager.registerListener(this, mSensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER),SensorManager.SENSOR_DELAY_NORMAL);
		
	}
	@Override
	public void onAccuracyChanged(Sensor arg0, int arg1) {
		// TODO Auto-generated method stub
		
	}
    //停止检测
    public void stop() {
    	mSensorManager.unregisterListener(this);
    }
	@Override
	public void onSensorChanged(SensorEvent event) {
		// TODO Auto-generated method stub
		int sensorType = event.sensor.getType();
		float[] values = event.values;
		//现在检测时间
        long currentUpdateTime = System.currentTimeMillis();
        //两次检测的时间间隔
        long timeInterval = currentUpdateTime - lastUpdateTime;
        //判断是否达到了检测时间间隔
        if(timeInterval > UPTATE_INTERVAL_TIME){	        	
        //现在的时间变成last时间
        lastUpdateTime = currentUpdateTime;	
	/*重力切换下一首歌曲*/	
		if(ch1.isChecked())
		{						
		if(sensorType==Sensor.TYPE_ACCELEROMETER)
		{       			
			if((Math.abs(values[0])>12.5||Math.abs(values[1])>12.5||Math.abs(values[2])>12.5)){
				
				count++;
				counta++;
				index=count;
		    if (count == res_file.length){
		    	count = 0;
		    	counta = 0;
		    	index=count;
		    	
		    }
		    try{
		    	mMediaPlayer.reset();
				mMediaPlayer = MediaPlayer.create(MainActivity.this,res_file[count]);
				mMediaPlayer.start();					
			} catch(Exception e) { }
		    int a = count +1;
		    Toast.makeText(MainActivity.this,"歌曲"+a+":"+name[counta],Toast.LENGTH_SHORT).show();
		    img.setImageResource(imgs[index]);
		    vibrator.vibrate(500);		//震动半秒
				}
			}	
		 
		}
	/*重力随机切换一首歌曲*/
        
		if(ch2.isChecked())
		{
		if(sensorType==Sensor.TYPE_ACCELEROMETER)
		{
			if((Math.abs(values[0])>12.5||Math.abs(values[1])>12.5|Math.abs(values[2])>12.5)){
				count=(int)(Math.random()*3);
				counta=count;
				index=count;
				int a = count+1;
		    try{
		    	mMediaPlayer.reset();
				mMediaPlayer = MediaPlayer.create(MainActivity.this,res_file[count]);
				mMediaPlayer.start();					
			} catch(Exception e) { }
		    Toast.makeText(MainActivity.this,"歌曲"+a+":"+name[counta],Toast.LENGTH_SHORT).show();
		    img.setImageResource(imgs[index]);
		    vibrator.vibrate(500);
				}
			}			
		}
	/*重力切换上一首歌曲*/		 
		if(ch3.isChecked())
		{
		if(sensorType==Sensor.TYPE_ACCELEROMETER)
		{
			if((Math.abs(values[0])>12.5||Math.abs(values[1])>12.5||Math.abs(values[2])>12.5)){	
				count--;
				counta=count;
				index=count;
		    if (count == -1){
		    	count = res_file.length-1;
		    	counta = name.length-1;
		    	index=count;
		    }
		    try{
		    	mMediaPlayer.reset();
				mMediaPlayer = MediaPlayer.create(MainActivity.this,res_file[count]);
				mMediaPlayer.start();					
			} catch(Exception e) { }
		    int a = count +1;
		    Toast.makeText(MainActivity.this,"歌曲"+a+":"+name[counta],Toast.LENGTH_SHORT).show();
		    img.setImageResource(imgs[index]);
		    vibrator.vibrate(500);
				}
			}	
		}			
       }
	}
}

activity_main.xml

 <?xml version="1.0" encoding="utf-8"?>
    	<AbsoluteLayout
        xmlns:android="http://schemas.android.com/apk/res/android"    
        android:layout_width="fill_parent"
        android:layout_height="fill_parent"
        android:background="#ff00ffff">
        <TextView 
            android:id="@+id/text1"
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:layout_x="5px"
            android:layout_y="10px"
            android:text="播放资源音乐"
            android:textSize="20sp"
            />
    
        <ImageButton
            android:id="@+id/Start"
            android:layout_width="39dp"
            android:layout_height="38dp"
            android:layout_x="96dp"
            android:layout_y="342dp"
            android:src="@drawable/bofang" />
    
        <ImageButton
            android:id="@+id/previous"
            android:layout_width="39dp"
            android:layout_height="38dp"
            android:layout_x="19dp"
            android:layout_y="342dp"
            android:src="@drawable/previous" />
    
        <ImageButton
            android:id="@+id/stop"
            android:layout_width="39dp"
            android:layout_height="38dp"
            android:layout_x="58dp"
            android:layout_y="342dp"
            android:src="@drawable/stop" />
    
        <ImageButton
            android:id="@+id/next"
            android:layout_width="39dp"
            android:layout_height="38dp"
            android:layout_x="172dp"
            android:layout_y="342dp"
            android:src="@drawable/next" />
    
        <ImageButton
            android:id="@+id/increase"
            android:layout_width="39dp"
            android:layout_height="38dp"
            android:layout_x="210dp"
            android:layout_y="342dp"
            android:src="@drawable/increase" />
    
        <ImageButton
            android:id="@+id/decrease"
            android:layout_width="39dp"
            android:layout_height="38dp"
            android:layout_x="248dp"
            android:layout_y="342dp"
            android:src="@drawable/decrease" />
    
        <ImageButton
            android:id="@+id/Pause"
            android:layout_width="44dp"
            android:layout_height="38dp"
            android:layout_x="130dp"
            android:layout_y="343dp"
            android:src="@drawable/pause" />
    
        <CheckBox
            android:id="@+id/ch1"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_x="11dp"
            android:layout_y="258dp"
            android:text="甩动手机切换下一首歌曲" />
    
        <CheckBox
            android:id="@+id/ch2"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_x="11dp"
            android:layout_y="390dp"
            android:text="甩动手机随机切换歌曲" />
    
        <CheckBox
            android:id="@+id/ch3"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_x="11dp"
            android:layout_y="297dp"
            android:text="甩动手机切换上一首歌曲" />
    
        <ImageView
            android:id="@+id/img"
            android:layout_width="259dp"
            android:layout_height="184dp"
            android:layout_x="20dp"
            android:layout_y="50dp"
            android:src="@drawable/img1" />
    	</AbsoluteLayout>

AndroidMainActivity:

 <uses-permission android:name="android.permission.VIBRATE"/>//设置允许使用震动效果的权限

附图:

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值