效果
代码
package com.javen.devicemange.CrazyOne.media; import android.media.AudioManager; import android.media.SoundPool; import android.os.Bundle; import android.support.annotation.Nullable; import android.support.v7.app.AppCompatActivity; import android.view.View; import android.widget.Button; import com.javen.devicemange.R; import java.util.HashMap; /** * Created by Administrator on 2017/2/24 0024. * 使用SoundPool播放较短的声音MP3(短信铃声) * SoundPool使用音效池的概念来管理多个短暂声音,支持多个声音同时播放 */ public class SoundPoolTest extends AppCompatActivity implements View.OnClickListener {private Button one; private Button two; HashMap<Integer, Integer> soundMap; private SoundPool soundPool; @Override protected void onCreate(@Nullable Bundle savedInstanceState) {super.onCreate(savedInstanceState); setContentView(R.layout.soundpooltest); initView(); soundMap = new HashMap<>(); //设置最多可以容纳10个音频流,音频的品质5 soundPool = new SoundPool(10, AudioManager.STREAM_SYSTEM, 5); //load方法加载指定音频文件,并返回所加载的音频id //使用HashMap来管理这些音频流 int oneId = soundPool.load(this, R.raw.one_music, 1); int twoId = soundPool.load(this, R.raw.two, 1); soundMap.put(1, oneId); soundMap.put(2, twoId); }private void initView() {one = (Button) findViewById(R.id.one); two = (Button) findViewById(R.id.two); one.setOnClickListener(this); two.setOnClickListener(this); }@Override public void onClick(View v) {switch (v.getId()) {case R.id.one://播放one_music音乐 soundPool.play(soundMap.get(1), 1, 1, 0, 0, 1); break; case R.id.two://播放two音乐 soundPool.play(soundMap.get(2), 1, 1, 0, 0, 1); break; }} }
raw目录
布局xml
<?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical"> <Button android:id="@+id/one" android:layout_width="match_parent" android:layout_height="wrap_content" android:text="播放音乐one"/> <Button android:id="@+id/two" android:layout_width="match_parent" android:layout_height="wrap_content" android:text="播放音乐two"/> </LinearLayout>
。。。