Android API learning soundpool and mediaplayer

Source: Internet
Author: User
From: http://dev.10086.cn/cmdn/wiki/index.php? Doc-view-5522.html

There are two ways to play audio on the Android platform:

1. soundpool-suitable for scenarios with short promotion and high response speed (game sound effects or button sounds)

2. mediaplayer-suitable for long and time-demanding scenarios

Bytes -------------------------------------------------------------------------------------------

Soundpool

1. Create a soundpool

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 Resources

One audio resource can be recorded in four ways:

Int load (assetfiledescriptor AFD, int priority)

Use an assetfiledescriptor object

Int load (context, int resid, int priority)

Use a resource ID

Int load (string path, int priority)

Load through the specified path

Int load (filedescriptor FD, long offset, long length, int priority)

Load with filedescriptor

* The API indicates that the priority parameter has no effect currently. We recommend that you set it to 1.

A single soundpool can manage multiple audios at the same time, so you can call the load function multiple times to record the results. If the recording succeeds, a non-zero soundid is returned, which is used to specify a specific audio during playback.

Eg.

Int soundid1 = soundpool. Load (this, R. Raw. sound1, 1 );

If (soundid1 = 0 ){

// Recording failed

} Else {

// Load successful

}

Int soundid2 = soundpool. Load (this, R. Raw. sound2, 1 );

...

Two streams are loaded and the returned soundid is recorded respectively.

Note that,

The stream loading process is a process of extracting audio into the original 16-bit PCM data, and a background thread is used for asynchronous processing. Therefore, it cannot be played immediately after initialization. It takes some time to wait.

3. Playback Control

You can use the following functions to control playback:

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

Play the sound of the specified audio and return a streamid.

Priority-stream priority. A higher value has a higher priority, which affects the processing of the stream when the number of simultaneous playback exceeds the maximum supported number;

Loop: the number of loop playback times. 0 indicates that the value is played once,-1 indicates that the loop is infinite, and other values include loop and 1 (for example, 3 indicates that the loop is played four times in total ).

Rate-the playback speed, range: 0.5-2.0 (0.5 is half the speed, 1.0 is the normal rate, 2.0 is the double rate)

Final void pause (INT streamid)

Pause the sound of the specified stream (streamid should be returned through play ).

Final void resume (INT streamid)

Continues playing the sound of the specified stream (streamid should be returned through play ).

Final void stop (INT streamid)

Terminate the sound effect of the specified stream (streamid should be returned through play ).

Note that,

1. the play () function transmits a soundid returned by load () to point to a recorded audio resource. If the playback is successful, a non-0 streamid is returned. It points to a successful stream; A single soundid can call play () multiple times to obtain multiple different streamids (as long as they do not exceed the maximum number of simultaneous playback );

2. Pause (), resume (), and stop () are for stream playback operations, and the streamid returned by play () is passed;

3. The priority parameter in play () takes effect only when the number of streams played at the same time exceeds the preset maximum. The manager will automatically terminate the stream with a lower priority. If multiple streams with the same priority are processed based on their creation events, the newly created streams will be terminated if they are of the minimum age;

4. In any case, it is necessary to manually stop playing and release resources when the program exits.

Eg.

// Play the soundid1 sound effect here-the priority is 0 (lowest), infinite loop, normal rate.

Int streamid = soundpool. Play (soundid1, 1.0, 1.0, 0,-1, 1.0 );

If (streamid = 0 ){

// Playback failed

} Else {

// Playback successful

}

...

// Pause the playing of soundid1

Soundpool. Pause (streamid );

...

// Resume playing soundid1

Soundpool. Resume (streamid );

...

// Stop the playback. Remember to stop the playback manually when the loop is-1.

Soundpool. Stop (streamid );

* The API indicates that even if an invalid soundid/streamid (operation failed or pointing to an invalid Resource) is used to call related functions, it will not cause errors, which can reduce the logic processing.

4. More property settings

It is actually the independent settings of some parameters in paly:

Final void setloop (INT streamid, int loop)

Sets the loop of the specified stream.

Final void setvolume (INT streamid, float leftvolume, float rightvolume)

Sets the volume of the specified stream.

Final void setpriority (INT streamid, int priority)

Sets the priority of the specified playback stream. The role of priority is described above.

Final void setrate (INT streamid, float rate)

Set the speed of the specified stream to 0.5-2.0.

5. release resources

Operational functions include:

Final Boolean unload (INT soundid)

Detaches a specified Audio Resource.

Final void release ()

Releases all audio Resources in the soundpool.

-Summary-

A soundpool can:

1. manage multiple audio resources. If the load () function succeeds, a non-zero soundid is returned;

2. play multiple audios at the same time. If the play () function succeeds, a non-0 streamid is returned;

3. Pause (), resume (), stop () and other operations are for streamid (Stream playback;

4. When it is set to an infinite loop, you must manually call stop () to terminate the playback;

5. The priority of the playback stream (the priority parameter in play () takes effect only when the number of simultaneous playback exceeds the set maximum;

6. You do not need to consider the life cycle of the playing stream (triggered by play) in the program. Invalid soundid/streamid will not cause program errors.

Bytes -------------------------------------------------------------------------------------------

Mediaplayer

You can create a mediaplayer object through the new or convenient static create function group.

Comparison of the two methods:

New mediaplayer ()

1. After the call is successful, the mediaplayer will be in the idle state;

2. setdatasource supports resource paths in string (PATH), Uri, and filedescriptor formats;

3. You need to manually call prepare () to play the video.

Mediaplayer. Create (...)

1. After the call is successful, the mediaplayer will be in the prepared State;

2. Create supports resource paths in int (resid) and Uri formats;

3. You can directly play the video without calling prepare () again.
Key points:

1. If the operation MP. setdatasource ("/sdcard/testcard") is incorrect, // directly passing the URL is also possible, the buffer is automatically processed.

} Catch (illegalargumentexception e ){

E. printstacktrace ();

} Catch (illegalstateexception e ){

// If setdatasource is called in a non-Idle State, this exception will occur.

E. printstacktrace ();

} Catch (ioexception e ){

E. printstacktrace ();

}

// Set the necessary listener

MP. setonpreparedlistener (New onpreparedlistener (){

@ Override

Public void onprepared (mediaplayer MP ){

// This ensures that the player is in the prepared state, and triggering start is the most suitable

MP. Start ();

}

});

MP. setoncompletionlistener (New oncompletionlistener (){

@ Override

Public void oncompletion (mediaplayer MP ){

// Normal playback ends. You can trigger the next playback.

}

});

MP. setonerrorlistener (New onerrorlistener (){

@ Override

Public Boolean onerror (mediaplayer MP, int what, intextra ){

// Errors caused by Operation errors or other causes will be notified here

Return true;

}

});

// Connect and load Resources

Try {

MP. Prepare ();

// MP. prepareasync () This is also possible. This is asynchronous processing. The above is synchronous processing. onpreparedlistener. onprepared () prevails when loading is complete.

} Catch (illegalstateexception e ){

E. printstacktrace ();

} Catch (ioexception e ){

E. printstacktrace ();

}

// MP. Start (); // It is recommended that this function be triggered in the onpreparedlistener. onprepared () callback, especially when asynchronous loading is used.

/**

* Other operations...

*/

// Stop playing and release resources

Try {

MP. Stop (); // This is necessary. If you set loop playback, otherwise the program exits and continues playing the music in the background...

MP. Release ();

} Catch (illegalstateexception e ){

E. printstacktrace ();

}

// The player created through new is in the idle state

As a result, the mediaplayer is in the error state. You can use the reset () function to restore it to the idle state, and then re-Execute initialization operations such as setdatasource (PS: if it is created by binding the resource ID through the create function, it will be depressing ...);

2. the API indicates that although the mediaplayer after reset is similar to the new one, there are subtle differences:

In both cases, the player is in the idle state. getcurrentposition (), getduration (), getvideoheight (), getvideowidth (), setaudiostreamtype (INT), setlooping (Boolean ), setvolume (float, float), pause (), start (), stop (), seekto (INT), prepare (), and prepareasync () all belong to programming errors. When these functions are called after mediaplayer is created, the onerrorlistener. onerror ()
The callback function will not be called by the internal player engine, and the player status remains unchanged. However, if the onerrorlistener is specified after the reset () function is called. the onerror () callback function will be called by the internal player engine (internal playback engine), and the player status will change to error.

3. Call the release () function to release resources immediately after use. If the operation succeeds, the mediaplayer object is in the end state, and no operations can be performed unless the mediaplayer object is re-created.

For more details, use the new method to create an example:

Java code

// The player created through new is in the idle state

Mediaplayer MP = new mediaplayer ();

If (MP = NULL ){

// New creation may return NULL values, which is a good habit of detection.

Return;

}

// Set the resource path. If the execution succeeds, the player will be in the initialized state.

Try {

Mediaplayer MP = new mediaplayer ();

If (MP = NULL ){

// New creation may return NULL values, which is a good habit of detection.

Return;

}

// Set the resource path. If the execution succeeds, the player will be in the initialized state.

Try {

MP. setdatasource ("/sdcard/testcard"); // you can directly upload a URL to automatically process the buffer.

} Catch (illegalargumentexception e ){

E. printstacktrace ();

} Catch (illegalstateexception e ){

// If setdatasource is called in a non-Idle State, this exception will occur.

E. printstacktrace ();

} Catch (ioexception e ){

E. printstacktrace ();

}

// Set the necessary listener

MP. setonpreparedlistener (New onpreparedlistener (){

@ Override

Public void onprepared (mediaplayer MP ){

// This ensures that the player is in the prepared state, and triggering start is the most suitable

MP. Start ();

}

});

MP. setoncompletionlistener (New oncompletionlistener (){

@ Override

Public void oncompletion (mediaplayer MP ){

// Normal playback ends. You can trigger the next playback.

}

});

MP. setonerrorlistener (New onerrorlistener (){

@ Override

Public Boolean onerror (mediaplayer MP, int what, intextra ){

// Errors caused by Operation errors or other causes will be notified here

Return true;

}

});

// Connect and load Resources

Try {

MP. Prepare ();

// MP. prepareasync () This is also possible. This is asynchronous processing. The above is synchronous processing. onpreparedlistener. onprepared () prevails when loading is complete.

} Catch (illegalstateexception e ){

E. printstacktrace ();

} Catch (ioexception e ){

E. printstacktrace ();

}

// MP. Start (); // It is recommended that this function be triggered in the onpreparedlistener. onprepared () callback, especially when asynchronous loading is used.

/**

* Other operations...

*/

// Stop playing and release resources

Try {

MP. Stop (); // This is necessary. If you set loop playback, otherwise the program exits and continues playing the music in the background...

MP. Release ();

} Catch (illegalstateexception e ){

E. printstacktrace ();

}

Playing control is basically the same as soundpool:

Start (), pause (), stop (), seekto (), setlooping ()...

It should be noted that the loop playback settings are different from those of soundpool. You cannot specify the number of loops, but a Boolean value that specifies whether loop playback is performed...

For more functions, see the API documentation.

Related Article

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.