Android多媒体之SoundPool
生活随笔
收集整理的這篇文章主要介紹了
Android多媒体之SoundPool
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
用soundpool可以播一些短的反應速度要求高的聲音,
比如游戲中的爆破聲,而mediaplayer適合播放長點的。
1. SoundPool載入音樂文件使用了獨立的線程,不會阻塞UI主線程的操作。但是這里如果音效文件過大沒有載入完成,我們調用play方法時可能產生嚴 重的后果,這里Android SDK提供了一個SoundPool.OnLoadCompleteListener類來幫助我們了解媒體文件是否載入完成,我們重載 onLoadComplete(SoundPool soundPool, int sampleId, int status) 方法即可獲得。
2. 從上面的onLoadComplete方法可以看出該類有很多參數,比如類似id,是的SoundPool在load時可以處理多個媒體一次初始化并放入內存中,這里效率比MediaPlayer高了很多。 人人
3. SoundPool類支持同時播放多個音效,這對于游戲來說是十分必要的,而MediaPlayer類是同步執行的只能一個文件一個文件的播放。
?
<LinearLayout 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:orientation="vertical" ><Buttonandroid:id="@+id/play01"android:layout_width="wrap_content"android:layout_height="wrap_content"android:text="play 01" /><Buttonandroid:id="@+id/play02"android:layout_width="wrap_content"android:layout_height="wrap_content"android:text="play 02" /></LinearLayout> package com.example.soundpooldemo;import java.util.HashMap; import java.util.Map;import android.media.AudioManager; import android.media.SoundPool; import android.media.SoundPool.OnLoadCompleteListener; import android.os.Bundle; import android.annotation.SuppressLint; import android.app.Activity; import android.view.Menu; import android.view.View; import android.view.View.OnClickListener; import android.widget.Button; import android.widget.Toast;@SuppressLint("UseSparseArrays") public class MainActivity extends Activity implements OnClickListener {private Button player1;private Button player2;private SoundPool sp;private Map<Integer,Integer> soundMap = new HashMap<Integer,Integer>();private int loadFlag = 0;@Overrideprotected void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);setContentView(R.layout.activity_main);sp = new SoundPool(4, AudioManager.STREAM_MUSIC, 5);soundMap.put(1, sp.load(this, R.raw.xxxx, 1));soundMap.put(2, sp.load(this, R.raw.yyyy, 1));sp.setOnLoadCompleteListener(new OnLoadCompleteListener() {@Overridepublic void onLoadComplete(SoundPool soundPool, int sampleId, int status) {//判斷是否加載完loadFlag = 1;}});player1 = (Button)findViewById(R.id.play01);player2 = (Button)findViewById(R.id.play02);player1.setOnClickListener(this);player2.setOnClickListener(this);}@Overridepublic boolean onCreateOptionsMenu(Menu menu) {getMenuInflater().inflate(R.menu.main, menu);return true;}@Overridepublic void onClick(View v) {if(loadFlag == 0)Toast.makeText(this, "音頻正在加載中......", Toast.LENGTH_SHORT).show();else{switch(v.getId()){case R.id.play01:sp.play(soundMap.get(1), 1, 1, 1, 0, 1);break;case R.id.play02:sp.play(soundMap.get(2), 1, 1, 1, 0, 1);}}}}?
轉載于:https://www.cnblogs.com/Bigmouse123/p/3345802.html
總結
以上是生活随笔為你收集整理的Android多媒体之SoundPool的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: IOS7新增120*120Icon图标
- 下一篇: java学习面向对象之内部类