为程序的按钮添加按键声音能更好的亲和用户,产生更好的使用体验,下面就是为按键添加声音的方法:

[java]  view plain copy
  1. public class MainActivity extends Activity {   
  2.     private Button mButton01;   
  3.     private SoundPool sp;//声明一个SoundPool   
  4.     private int music;//定义一个整型用load();来设置suondID    
  5.   
  6.     @Override   
  7.     public void onCreate(Bundle savedInstanceState) {   
  8.   
  9.         super.onCreate(savedInstanceState);   
  10.         setContentView(R.layout.activity_main);   
  11.         mButton01=(Button)findViewById(R.id.mButton01);   
  12.         sp= new SoundPool(10, AudioManager.STREAM_SYSTEM, 5);//第一个参数为同时播放数据流的最大个数,第二数据流类型,第三为声音质量   
  13.         music = sp.load(this, R.raw.start, 1); //把你的声音素材放到res/raw里,第2个参数即为资源文件,第3个为音乐的优先级   
  14.   
  15.         mButton01.setOnClickListener(new OnClickListener(){   
  16.             @Override   
  17.            public void onClick(View v) {   
  18.              sp.play(music, 11001);   
  19.        }  
  20.     }  
  21.   }  
  22. }  
在实现的过程中,我发现不同的Android机器对声音资源文件的格式要求不同

当声音资源文件格式为wma时,Android虚拟机上测试,按键可以发出声音。

在真机上测试(魅族M9),logcat显示如下:

Unable to load sample: (null)

W/SoundPool sample 1 not READY

按下按键并没有声音。

查找资料发现,在使用SoundPool时,不同的机器对文件格式要求不同。

于是将资源文件转为mp3格式类型,但是测试发现,这次的情况恰恰相反,即真机可以播放,虚拟机不行。

想到之前所做项目中,声音资源的格式为ogg,没有出现过类似问题。果断转换、、进行测试,真机、虚拟机都可以啦!!

更多相关文章

  1. android 极光推送 自定义声音
  2. No resource found that matches the given name 'Theme.AppComp
  3. Android(安卓)adb中的操作命令
  4. Android(安卓)4.0 隐藏虚拟按键(导航栏)的方法
  5. Android(安卓)开发(三)使用Stirngs资源文件的技巧
  6. 按钮的点击效果(按钮背景图片变换)
  7. Android字符串资源
  8. android studio 官方用户指南翻译学习(四)创建 Android(安卓)libra
  9. Android中的string资源占位符及Plurals string

随机推荐

  1. Install Android(安卓)Composite ADB Int
  2. Android四大组件Service之bindService启
  3. android native call only, no third par
  4. Android实践之TabActivity
  5. How to parse / read JSON data into a A
  6. android 手机判断是否在充电 如断电自动
  7. AppCompat does not support the current
  8. Android中ActionBar居中
  9. android 从assets和res中读取文件
  10. Android(安卓)NDK 配置与打包