一徐绑、.Assets的使用
可加載不同類型的文件伐割,不會像Android的資源管理系統(tǒng)一樣一個一個去處理诫咱,效率低下笙隙,所以才用Assets來加載不同類型的聲音。
1.導(dǎo)入文件到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能加載一批聲音資源到內(nèi)存中竟痰,并支持同時播放多個音頻文件
1.創(chuàng)建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>
四掏呼、按鈕優(yōu)化
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>