Android之SoundPool背景音乐

来源:互联网 发布:windows资源管理器停止 编辑:程序博客网 时间:2024/06/06 05:06
public class SimpleActivity extends AppCompatActivity {    SoundPool sp;    HashMap<Integer, Integer> hm;    int currStreanId;    @Bind(R.id.button2)    Button button2;    @Bind(R.id.button3)    Button button3;    @Override    protected void onCreate(Bundle savedInstanceState) {        super.onCreate(savedInstanceState);        setContentView(R.layout.activity_simple);        ButterKnife.bind(this);        initSoundPool();    }    @OnClick({R.id.button2, R.id.button3})    public void onClick(View view) {        switch (view.getId()) {            case R.id.button2:                playSoud(1,-1);//播放次数,-1表示无限重复,0表示一次,1表示两次,以此类推。                break;            case R.id.button3:                sp.stop(currStreanId);                break;        }    }    /**     * 由于SoundPool只适合播放不大于7秒的文件,实际游戏开发中采用的是MediaPlay来播放背景音乐     *      *      *///初始化声音池    private void initSoundPool() {        sp = new SoundPool(4, AudioManager.STREAM_MUSIC, 0);        hm = new HashMap<>();        hm.put(1, sp.load(this, R.raw.siml, 1));    }    //播放声音的方法    private void playSoud(int sound, int loop) {        AudioManager am = (AudioManager) this.getSystemService(Context.AUDIO_SERVICE);//获取当前音量        float streamVolumeCurrent = am.getStreamVolume(AudioManager.STREAM_MUSIC);        float streamVolumeMax = am.getStreamMaxVolume(AudioManager.STREAM_MUSIC);//计算获得系统最大音量        float volume = streamVolumeCurrent/streamVolumeMax;//计算得到的播放音量        currStreanId = sp.play(hm.get(sound), volume, volume, 1, loop, 1.0f);    }}
<?xml version="1.0" encoding="utf-8"?><RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"    xmlns:tools="http://schemas.android.com/tools"    android:layout_width="match_parent"    android:layout_height="match_parent"    android:paddingBottom="@dimen/activity_vertical_margin"    android:paddingLeft="@dimen/activity_horizontal_margin"    android:paddingRight="@dimen/activity_horizontal_margin"    android:paddingTop="@dimen/activity_vertical_margin"    tools:context="com.yang.yin.yinyangapplication.SimpleActivity">    <Button        android:layout_width="wrap_content"        android:layout_height="wrap_content"        android:text="@string/playmu"        android:id="@+id/button2"        android:layout_alignParentTop="true"        android:layout_alignParentLeft="true"        android:layout_alignParentStart="true"        android:layout_marginTop="130dp" />    <Button        android:layout_width="wrap_content"        android:layout_height="wrap_content"        android:text="@string/stopmu"        android:id="@+id/button3"        android:layout_below="@+id/button2"        android:layout_alignParentLeft="true"        android:layout_alignParentStart="true" /></RelativeLayout>

这里写图片描述

0 0
原创粉丝点击