Play a short music file in soundpool

Source: Internet
Author: User

When developing Android applications, we may often need to play multimedia audio files. Generally, the mediaplayer class is used. However, this class occupies a large amount of resources and may not be suitable for games and other applications, soundpool class in the SDK android. media. soundpool, as its name implies, is the meaning of the sound pool. It mainly plays a few short sound clips that can be loaded from program resources or file systems. Compared with the mediaplayer class, it can use less CPU resources and reduce response latency. Compared with other audio playback categories, soundpool allows you to set parameters such as sound quality, volume, and playback ratio. In addition, it can manage multiple audio streams at the same time. Each stream has its own ID, and the management of an audio stream is performed by ID.
Basic usage of soundpool:


1. Create a soundpool


Create a soundpool object: New soundpool (INT maxstreams, int streamtype, int srcquality)


Public soundpool (INT maxstream, int streamtype, int srcquality)


Maxstream -- maximum number of streams simultaneously played


Streamtype -- stream type, which is generally stream_music (listed in the audiomanager class)


Srcquality -- sampling rate conversion quality. No effect currently. Use 0 as the default value.


Eg.


Soundpool = new soundpool (3, audiomanager. stream_music, 0 );


Creates a soundpool that supports simultaneous playback of up to three streams and marks the type as music.


2. Load audio streams from resources or files: load (context, int resid, int priority );


Loading soundpool:


Int load (context, int resid, int priority) // load data from the APK Resource


Int load (filedescriptor FD, long offset, long length, int priority) // load data from the filedescriptor object


Int load (assetfiledescriptor AFD, int priority) // load data from the asset object


Int load (string path, int priority) // load data from the complete file path


The last parameter is the priority.


Generally, multiple voices are put in hashmap, for example


Soundpool = new soundpool (4, audiomanager. stream_music, 100 );


Soundpoolmap = new hashmap <integer, integer> ();


Soundpoolmap. Put (1, soundpool. Load (this, R. Raw. Dingdong, 1 ));


3. Play (INT soundid, float leftvolume, float rightvolume, int priority, int loop, float rate );


Play (INT soundid, float leftvolume, float rightvolume, int priority, int loop, float rate ),


Leftvolume and rightvolume indicate the Left and Right volume,


Priority indicates priority,


Loop indicates the number of cycles,


Rate indicates the speed. For example, the minimum rate is 0.5 and the maximum value is. 1 indicates the normal speed.


Sp. Play (soundid, 1, 1, 0, 0, 1 );


You can use the pause (INT streamid) method to stop the operation. Both the streamid and soundid are constructing


The first parameter indicates the total number, and the ID starts from 0.

Note:

1. soundpool can only apply for a maximum of 1 MB of memory space, which means that we can only use some very short sound clips instead of playing songs or playing background music.

2. soundpool provides pause and stop methods, but it is recommended that you do not use these methods easily, because sometimes they may cause your program to terminate inexplicably. Android Development Network recommends that you do more test work when using these two methods. Some friends report that they do not stop playing the sound immediately, but stop playing the data in the buffer zone, it may take a second to play.

3. soundpool efficiency issues. In fact, soundpool efficiency is good in these playing classes, which may affect the user experience. Maybe this does not care about soundpool itself, because the latency in droid with better performance is acceptable.

4. Although some files are small, the decoded 16-bit PCM may play a very short part of the sound for more than 1 MB. Files that exceed 1 MB cannot be played.

Run the code below.

Layout File

 

<Linearlayout xmlns: Android = "http://schemas.android.com/apk/res/android" xmlns: Tools = "http://schemas.android.com/tools" Android: Id = "@ + ID/linearlayout1" Android: layout_width = "match_parent" Android: layout_height = "match_parent" Android: Orientation = "vertical" tools: context = ". mainactivity "> <button Android: Id =" @ + ID/startbutton "Android: layout_width =" match_parent "Android: layout_height =" wrap_content "Android: TEXT = "start playing"/> <button Android: Id = "@ + ID/pausebutton" Android: layout_width = "match_parent" Android: layout_height = "wrap_content" Android: TEXT = "pause playback"/> <button Android: Id = "@ + ID/stopbutton" Android: layout_width = "match_parent" Android: layout_height = "wrap_content" Android: TEXT = "Stop playing"/> </linearlayout>

Source code

 

 

Package COM. example. testsoundpool; import Java. util. hashmap; import android. r. bool; import android. media. audiomanager; import android. media. soundpool; import android. media. soundpool. onloadcompletelistener; 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 mainactivity ex Tends activity implements onclicklistener {private soundpool sp = NULL; // declare a reference to a soundpool private hashmap <integer, integer> Hm; // declare a hashmap to store the sound resource private int currentstreamid; // streamidprivate button startplaybutton of the current playback; // Private button pauseplaybutton of the playback button; // Private button stopplaybutton of the pause button; // Private Boolean isfinishedload = false; // check whether the music file has been loaded. Private Boolean ispauseplay = false; // whether to pause playing @ overridepr Otected void oncreate (bundle savedinstancestate) {super. oncreate (savedinstancestate); setcontentview (R. layout. activity_main); // click the response function startplaybutton = (button) findviewbyid (R. id. startbutton); pauseplaybutton = (button) findviewbyid (R. id. pausebutton); stopplaybutton = (button) findviewbyid (R. id. stopbutton); startplaybutton. setonclicklistener (this); pauseplaybutton. setonclicklistener (this); stopplaybutton. setonc Licklistener (this); // initialize soundpoolinitsoundpool () ;}@ overridepublic Boolean oncreateoptionsmenu (menu) {// inflate the menu; this adds items to the action bar if it is present. getmenuinflater (). inflate (R. menu. activity_main, menu); Return true;} // button response function @ overridepublic void onclick (view v) {// todo auto-generated method stubswitch (v. GETID () {case R. id. startbutton: playsound (); // The Dudu file is decoded to 1. The size of the 6-bit PCM Data exceeds 1 MB of the soundpool buffer, and the loop cannot be completed. The whole song // playsound (2,-1) cannot be played. // The musictestbreak can be played cyclically; case R. id. pausebutton: ispauseplay = true; SP. pause (currentstreamid); break; case R. id. stopbutton: ispauseplay = false; SP. stop (currentstreamid); break; default: system. out. println ("Switch default"); break;} public void initsoundpool () {system. out. println ("+ initsoundpool +"); SP = new soundpool (4, audiomanager. stream_music, 0); // create a sound Pool object sp. setonloadcompletelistener (New onloadcompletelistener () {@ overridepublic void onloadcomplete (soundpool, int sampleid, int status) {// todo auto-generated method stubisfinishedload = true; system. out. println ("setonloadcompletelistener") ;}}); HM = new hashmap <integer, integer> (); // create a hashmap object HM. put (1, SP. load (this, R. raw. dudu, 0); // load the Dudu sound file and set it to file 1 and put it in hmhm. put (2, SP. load (this, R. raw. musi Ctest, 0); // load the musictest sound file and set it to file 2 and put it in hmsystem. out. println ("-initsoundpool-");} // The number of songs in the sound HM // whether loop 0 does not loop-1 loop public void playsound (INT sound, int loop) {string log; If (! Ispauseplay) {audiomanager AM = (audiomanager) This. getsystemservice (audio_service); float currentstreamvolume = aM. getstreamvolume (audiomanager. stream_music); float maxstreamvolume = aM. getstreammaxvolume (audiomanager. stream_music); float setvolume = (float) currentstreamvolume/maxstreamvolume; If (isfinishedload) currentstreamid = sp. play (HM. get (sound), setvolume, setvolume, 1, loop, 1.0f); log = "playsound currentstreamid:" + String. valueof (currentstreamid); system. out. println (log);} else {ispauseplay = false; SP. resume (currentstreamid) ;}}@ overrideprotected void ondestroy () {// todo auto-generated method stubsuper. ondestroy (); SP. unload (currentstreamid); SP. release ();}}

Source code

 

 

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.