一、.Assets的使用
可加载不同类型的文件,不会像Android的资源管理系统一样一个一个去处理,效率低下,所以才用Assets来加载不同类型的声音。
1.导入文件到assets中
导入下载好的声音文件2.处理assets
public class BeatBox {
private static final String TAG ="BeatBox";
private static final String SOUNDS_FOLDER = "sample_sounds";
private AssetManager mAssets;
public BeatBox(Context context){
mAssets = context.getAssets();
loadSounds();
}
}
3.使用assets
public class Sound {
private String mAssetPath;
private String mName;
private Integer mSoundId;
public Sound(String assetPath){
mAssetPath = assetPath;
String[] components = assetPath.split("/");
String filename = components[components.length - 1];
mName =filename.replace(".ogg","");
}
public String getAssetPath(){
return mAssetPath;
}
public String getName(){
return mName;
}
public Integer getSoundId(){
return mSoundId;
}
public void setSoundId(Integer soundId){
mSoundId = soundId;
}
}
二、使用SoundPool播放音频
SoundPool能加载一批声音资源到内存中,并支持同时播放多个音频文件
1.创建SoundPool
mSoundPool = new SoundPool(MAX_SOUNDS, AudioManager.STREAM_MUSIC,0);
2.加载音频文件
private void load(Sound sound) throws IOException{
AssetFileDescriptor afd = mAssets.openFd(sound.getAssetPath());
int soundId = mSoundPool.load(afd,1);
sound.setSoundId(soundId);
}
3.播放音频
public void play(Sound sound){
Integer soundId = sound.getSoundId();
if (soundId == null){
return;
}
mSoundPool.play(soundId,1.0f,1.0f,1,0,1.0f);
}
4.释放音频
@Override
public void onDestroy(){
super.onDestroy();
mBeatBox.release();
}
三、样式与主题
1.样式
<style name="BeatBoxButton" parent="android:style/Widget.Holo.Button">
<item name="android:background">@drawable/button_beat_box</item>
</style>
2.主题
<application
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:supportsRtl="true"
android:theme="@style/AppTheme">
<activity android:name=".BeatBoxActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN"/>
<category android:name="android.intent.category.LAUNCHER"/>
</intent-filter>
</activity>
</application>
四、按钮优化
1.圆形按钮
<shape xmlns:android="http://schemas.android.com/apk/res/android"
android:shape="oval">
<solid
android:color="@color/dark_bule"/>
</shape>
2.按下按钮的效果
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item android:drawable="@drawable/button_beat_box_pressed"
android:state_pressed="true"/>
<item android:drawable="@drawable/button_beat_box_normal"/>
</selector>
网友评论