In Android development, we often use mediaplayer to play audio files. However, mediaplayer has some shortcomings, such as high resource usage, long latency, and not support simultaneous playback of multiple audios. These disadvantages determine that mediaplayer is not ideal in some scenarios, for example, in game development with relatively high time precision.
In game development, we often need to play some game sound effects (such as bullet explosion and object impact). These sound effects are characterized by short promotion, intensive, and low latency. In this scenario, we can use soundpool instead of mediaplayer to play these sound effects.
To use soundpool, follow these steps:
1. Create a raw folder in res and put the audio to be played into it;
2. initialize the soundpool instance;
3. Call the play function of soundpool to play the video.
Several important functions:
Soundpool Constructor
Public soundpool (INT maxstreams, int streamtype, int srcquality)
Parameters:
Max number of audios simultaneously played by maxstreams
Streamtype: specifies the type of the audio stream. Generally, stream_music is used.
Srcquality the sample-Rate Converter quality. currently has no effect. Use 0 for the default.
Sound playback function:
Public void playsounds (INT sound, int number ){
// Instantiate the audiomanager object to control the sound
Audiomanager AM = (audiomanager) This. getsystemservice (this. audio_service );
// Maximum volume
Float audiomaxvolumn = aM. getstreammaxvolume (audiomanager. stream_music );
// Current volume
Float audiocurrentvolumn = aM. getstreamvolume (audiomanager. stream_music );
Float volumnratio = audiocurrentvolumn/audiomaxvolumn;
// Play
Sp. Play (spmap. Get (sound), // sound resource
Volumnratio, // left audio
Volumnratio, // right channel
1, // priority, 0 lowest
Number, // number of cycles. 0 indicates no loop, and-1 indicates permanent loop.
1); // playback speed, ranging from 0.5 to 2.0. 1 indicates normal speed
}
Code list
Main activity:
package com.example.soundpool;import java.util.HashMap;import android.media.AudioManager;import android.media.SoundPool;import android.os.Bundle;import android.app.Activity;import android.view.Menu;import android.view.View;import android.view.View.OnClickListener;import android.widget.Button;public class SPActivity extends Activity {private Button playBtn;private Button pauseBtn;private SoundPool sp;private HashMap<Integer,Integer> spMap;@Overridepublic void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);setContentView(R.layout.activity_sp);playBtn=(Button)findViewById(R.id.button1);pauseBtn=(Button)findViewById(R.id.button2);sp=new SoundPool(2,AudioManager.STREAM_MUSIC,0);spMap = new HashMap<Integer,Integer>();spMap.put(1, sp.load(this, R.raw.sound1, 1));playBtn.setOnClickListener(new OnClickListener() { public void onClick(View v) { // TODO Auto-generated method stub playSounds(1,1); } });pauseBtn.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { // TODO Auto-generated method stub sp.pause(spMap.get(1)); } }); }@Overridepublic boolean onCreateOptionsMenu(Menu menu) {getMenuInflater().inflate(R.menu.activity_sp, menu);return true;}public void playSounds(int sound, int number){ AudioManager am = (AudioManager)this.getSystemService(this.AUDIO_SERVICE); float audioMaxVolumn = am.getStreamMaxVolume(AudioManager.STREAM_MUSIC); float audioCurrentVolumn = am.getStreamVolume(AudioManager.STREAM_MUSIC); float volumnRatio = audioCurrentVolumn/audioMaxVolumn; sp.play(spMap.get(sound), volumnRatio, volumnRatio, 1, number, 1); }}
Layout code:
<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" > <Button android:id="@+id/button1" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_alignLeft="@+id/textView1" android:layout_below="@+id/textView1" android:layout_marginTop="42dp" android:text="Play" /> <Button android:id="@+id/button2" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_alignBaseline="@+id/button1" android:layout_alignBottom="@+id/button1" android:layout_centerHorizontal="true" android:text="Pouse" /></RelativeLayout>
A small problem:
The pause button is easy to use during the first playback. After the first playback, it will no longer work:
It turns out that the ID corresponding to this stream needs to be returned by the play method. Later, I used mpresentplayid to store the stream ID returned by play. When I stopped the stream ID, I used mpresentplayid to replace it, then I output the value of mpresentplayid, and found that this value is 2 for the first time. the second is 4. Pay attention to this problem when using this method in the future.