How to play Audio with SoundPool in Android
This article mainly introduces the relevant knowledge of how to use SoundPool to play audio in Android, the content is detailed and easy to understand, the operation is simple and fast, and has a certain reference value. I believe you will have something to gain after reading this Android article on how to play audio using SoundPool. Let's take a look.
Use SoundPool to play sound effects
The SoundPool class can be used to manage and play audio resources in applications. These audio resources can be placed in storage files or included in programs. Generally speaking, SoundPool is used to play short sound effects, such as various sound effects in games.
First create a SoundPool object
Private SoundPool sp
And then
Create a Builder object with SoundPool.Builder builder
Set the maximum number of audio, setMaxStreams ()
Default audio type, setLegacyStreamType ()
Set the audio type, setAudioAttributes ()
If (Build.VERSION.SDK_INT > = 21) {SoundPool.Builder builder = new SoundPool.Builder (); builder.setMaxStreams (2); AudioAttributes.Builder attrBuilder = new AudioAttributes.Builder (); attrBuilder.setLegacyStreamType (AudioManager.STREAM_MUSIC); builder.setAudioAttributes (attrBuilder.build ()); sp = builder.build () } else {sp = new SoundPool (2, AudioManager.STREAM_SYSTEM, 0);}
Because SoundPool is out of date after API21 in Android, it is important to judge
Then load the audio file with load and play it with play
Int soundId1=sp.load (this,R.raw.winlog,1); int soundId2=sp.load (this,R.raw.lesson1,2); Button button1= (Button) findViewById (R.id.button1); button1.setOnClickListener (new View.OnClickListener () {@ Override public void onClick (View v) {sp.play (soundId1,1,1,1,0,1);}}) Button button2= (Button) findViewById (R.id.button2); button2.setOnClickListener (new View.OnClickListener () {@ Override public void onClick (View v) {sp.play (soundId2,2,1,1,0,1);}})
SoundPool also has other methods, such as
Pause (), pauses playback
Release (), which releases the audio resources loaded in SoundPool
Resume () to continue playing the paused video
SetLoop (), sets the number of times to repeat playback
SetVlume (), sets the volume
Stop (), stop playback
Unload (), uninstall audio resources
This is the end of the article on "how to play audio with SoundPool in Android". Thank you for reading! I believe you all have a certain understanding of "how to use SoundPool to play audio in Android". If you want to learn more, you are welcome to follow the industry information channel.