Mediaplayer for Android: Playing short-term audio effects with soundpool

Source: Internet
Author: User
[1] mediaplayer for normal audio playback
  • Mediaplayer plays normal audio files

 

Mediaplayer = new mediaplayer (); <br/> If (mediaplayer. isplaying () {<br/> mediaplayer. reset (); // reset to initial status <br/>}< br/> mediaplayer. setdatasource ("/mnt/sdcard/god.mp3"); <br/> mediaplayer. prepare (); // buffer <br/> mediaplayer. start (); // start or resume playback <br/> mediaplayer. pause (); // pause playback <br/> mediaplayer. start (); // Resume playback <br/> mediaplayer. stop (); // stop playing <br/> mediaplayer. release (); // release resources <br/> mediaplayer. setoncompletionlistener (New mediaplayer. oncompletionlistener () {// event of broadcasting completion <br/> @ override public void oncompletion (mediaplayer arg0) {<br/> mediaplayer. release (); <br/>}< br/>}); <br/> mediaplayer. setonerrorlistener (New mediaplayer. onerrorlistener () {// error handling event <br/> @ override public Boolean onerror (mediaplayer player, int arg1, int arg2) {<br/> mediaplayer. release (); <br/> return false; <br/>}< br/> }); 

  • Program example:

/** <Br/> * audio player <br/> * @ author Kay <br/> */<br/> public class playactivity extends activity <br/> {<br /> Private Static final string tag = "playactivity "; <br/> private edittext filenametext; <br/> private mediaplayer; <br/> private string filename; <br/> private int position; </P> <p> @ override <br/> Public void oncreate (bundle savedinstancestate) <br/>{< br/> super. oncreate (savedinst Ancestate); <br/> setcontentview (R. layout. main); <br/> filenametext = (edittext) This. findviewbyid (R. id. filename); </P> <p> // instantiate the mediaplayer <br/> mediaplayer = new mediaplayer (); <br/> buttonclicklistener listener = new buttonclicklistener (); <br/> // obtain four buttons <br/> button playbutton = (button) This. findviewbyid (R. id. play); <br/> button pausebutton = (button) This. findviewbyid (R. id. pause); <br/> butto N resetbutton = (button) This. findviewbyid (R. id. reset); <br/> button stopbutton = (button) This. findviewbyid (R. id. stop); <br/> // set the listening of the four buttons <br/> playbutton. setonclicklistener (listener); <br/> pausebutton. setonclicklistener (listener); <br/> resetbutton. setonclicklistener (listener); <br/> stopbutton. setonclicklistener (listener); <br/> log. I (TAG, "oncreate ()"); <br/>}</P> <p> @ override <br/> protected Void onrestoreinstancestate (bundle savedinstancestate) <br/>{< br/> This. filename = savedinstancestate. getstring ("FILENAME"); <br/> This. position = savedinstancestate. getint ("position"); <br/> super. onrestoreinstancestate (savedinstancestate); <br/> log. I (TAG, "onrestoreinstancestate ()"); <br/>}< br/> @ override <br/> protected void onsaveinstancestate (bundle outstate) <br/>{< br/> outstate. putstring ("fil Ename ", filename); <br/> outstate. putint ("position", position); <br/> super. onsaveinstancestate (outstate); <br/> log. I (TAG, "onsaveinstancestate ()"); <br/>}</P> <p> private void play () throws ioexception <br/>{< br/> // obtain the file path <br/> file audiofile = new file (environment. getexternalstoragedirectory (), filename); <br/> mediaplayer. reset (); <br/> mediaplayer. setdatasource (audiofile. getabsolutepath (); <br/> Medi Aplayer. prepare (); <br/> mediaplayer. start (); <br/>}</P> <p> // If a call arrives suddenly, stop playing music <br/> @ override <br/> protected void onpause () <br/>{< br/> If (mediaplayer. isplaying () <br/>{< br/> // Save the current playback point <br/> position = mediaplayer. getcurrentposition (); <br/> mediaplayer. stop (); <br/>}< br/> super. onpause (); <br/>}</P> <p> // <br/> @ override <br/> protected void onresume () <br/>{< br/> // if the phone number ends, continue playing music <br/> If (position> 0 & F Ilename! = NULL) <br/>{< br/> try <br/>{< br/> play (); <br/> mediaplayer. seekto (position); <br/> position = 0; <br/>}< br/> catch (ioexception e) <br/>{< br/> log. E (TAG, E. tostring (); <br/>}< br/> super. onresume (); <br/>}</P> <p> // destroy the mediaplayer <br/> @ override <br/> protected void ondestroy () <br/>{< br/> mediaplayer. release (); <br/> super. ondestroy (); <br/> log. I (TAG, "ondestroy ()"); <br/>}< br/> private final class buttonclicklistener implements view. onclicklistener <br/>{< br/> @ override <br/> Public void onclick (view V) <br/>{< br/> // obtain the content in the text box <br/> filename = filenametext. gettext (). tostring (); <br/> // get the button <br/> button = (button) V; <br/> try <br/> {<br/> // you can use the passed buttonid to determine the button type. <br/> switch (v. GETID () <br/>{< br/> case R. id. play: <br/> play (); <br/> break; </P> <p> case R. id. pause: <br/> If (mediaplayer. isplaying () <br/>{< br/> mediaplayer. pause (); <br/> button. settext (R. string. continue1); // display the text on this button as "continue" <br/>}< br/> else <br/>{< br/> mediaplayer. start (); // Resume playback <br/> button. settext (R. string. pause); <br/>}< br/> break; </P> <p> case R. id. reset: <br/> If (mediaplayer. isplaying () <br/>{< br/> mediaplayer. seekto (0); // start playing from 0 <br/>}< br/> else <br/>{< br/> play (); // if it is not played, start playing it <br/>}< br/> break; </P> <p> case R. id. stop: <br/> // if it is playing, stop it. <br/> If (mediaplayer. isplaying () <br/> mediaplayer. stop (); <br/> break; <br/>}< br/> catch (exception e) <br/>{< br/> log. E (TAG, E. tostring (); <br/>}< br/>} 

[2] Using soundpool for short-term sound effects

 

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.

Soundpool (Android. Media. soundpool) is called the sound pool. It is mainly used to play short sound clips and supports loading from program resources or file systems. Compared with mediaplayer, soundpool has the advantage of low CPU usage and low response latency. In addition, soundpool also allows you to set parameters such as sound quality, volume, and playback ratio, and allows you to manage multiple audio streams by ID.

  • Soundpool Defects

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. We recommend that you do as much test work as possible 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, but some friends test it in G1 with a latency of about ms, which may affect the user experience. Maybe this does not care about soundpool itself, because the latency in droid with better performance is acceptable.

Soundpool has these defects at present, but it also has an irreplaceable advantage. Based on these, we recommend that you use soundpool in the following scenarios: 1. audio Effect in the application (key tone, message, etc.) 2. intensive and transient sounds in the game (such as the simultaneous explosion of multiple ships)

  • Soundpool usage

 

 

 

Development steps:

1> Add a sound file to the res/raw directory of the project.

2> Create a soundpool object, call soundpool. Load () to load the sound effect, and call soundpool. Play () to play the specified sound effect file.

Public class audioactivity extends activity <br/>{< br/> private soundpool pool; <br/> @ override <br/> Public void oncreate (bundle savedinstancestate) <br/>{< br/> super. oncreate (savedinstancestate); <br/> setcontentview (R. layout. main); <br/> // The maximum number of audio streams in the specified sound pool is 10, and the sound quality is 5 <br/> pool = new soundpool (10, audiomanager. stream_system, 5); <br/> // load the audio stream and return the ID in the pool <br/> final int sourceid = pool. load (this, R. raw. PJ, 0); <br/> button = (button) This. findviewbyid (R. id. button); <br/> button. setonclicklistener (new view. onclicklistener () <br/> {<br/> Public void onclick (view v) <br/> {// play the audio. The second parameter is the left audio volume; the third parameter is the right-channel volume, the fourth parameter is the priority, the fifth parameter is the number of cycles, 0 is not the cycle,-1 is the cycle, and the sixth parameter is the speed, the lowest speed is 0.5. The highest speed is, which indicates the normal speed <br/> pool. play (sourceid, 1, 1, 0,-1, 1); <br/>}< br/>}); <br/>}< br/>} 

 

 

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.