Audio processing in android------Soundpool,mediarecorder,mediaplayer and Ringstone Summary

Source: Internet
Author: User

Soundpool can be used to broadcast a few short reaction speed requirements of high sound, such as the game of the blasting sound,

And the MediaPlayer is suitable for playing long points. Mediarecorder is mainly used for recording.


Soundpool Loading music files uses a separate thread that does not block the operation of the UI main thread.

But here, if the sound file is too large to load, we may have serious consequences when we call the play method,

Here ANDROIDSDK provides a Soundpool.onloadcompletelistener class to help us understand if a media file is loaded and finished,

We can get the overloaded onloadcomplete (soundpool soundpool, int sampleid, int status) method.

SampleID

The sample ID of the sound loaded.

Status

The status of the load operation (0 = success)


From the Onloadcomplete method above, we can see that the class has many parameters,

For example, Id,soundpool can handle multiple media initialization and into memory at load time.

The efficiency here is much higher than the MediaPlayer.


The Soundpool class supports simultaneous playback of multiple sound effects, which is necessary for the game,

While the MediaPlayer class is synchronous, only one file can be played in a single file.

Create:

Public Soundpool (int maxstream, intstreamtype, int srcquality)
maxstream--the maximum number of simultaneous streams to be played
streamtype--type of stream, typically stream_music (specifically listed in the Audiomanager Class)
srcquality--sample rate conversion quality, currently no effect, use 0 as the default value
  

eg
Soundpool Soundpool = new Soundpool (3, audiomanager.stream_music,0);
Created a soundpool that supports simultaneous playback of up to 3 streams, with types marked as music.

Generally put multiple sounds into the hashmap, such as
Soundpool = new Soundpool (4, audiomanager.stream_music,100);
Soundpoolmap = new hashmap<integer,integer> ();
Soundpoolmap.put (1, Soundpool.load (this, r.raw.dingdong,1));

Load:
int load (context context, INTRESID, int priority)//load from APK resource
int load (filedescriptor fd, long offset, long length, intpriority)//load from FileDescriptor object
int load (assetfiledescriptor afd, int priority)//load from Asset object
int load (String path, int priority)//loaded from full file path name
The last parameter is a priority.


Play:
Play (int soundid, float leftvolume, float rightvolume, int priority, Int. loop,float rate),

where Leftvolume and Rightvolume represent the volume, priority is prioritized, loop indicates the number of loops, rate represents the speed,

Such as
Rate min. 0.5 up to 2, 1 for normal speed
Sp.play (Soundid, 1, 1, 1, 0, 1.0f);


Instead of stopping, you can use the pause (int streamid) method,

The Streamid and Soundid here Specify the total number in the first parameter of the constructed Soundpool class, and the ID starts at 0.

Get Audiomanager Object

Audiomanager Maudiomanager = (audiomanager) getsystemservice (audio_service);

Play sound

Maudiomanager.playsoundeffect (Audiomanager. Fx_key_click);

General Audiomanager in Onresume and OnStop methods need to be treated as follows:

Get ready-to-play sound effects@overrideprotected void Onresume () {super.onresume (); Maudiomanager.setspeakerphoneon ( true); Maudiomanager.loadsoundeffects ();} Release Resources & Clean up@overrideprotected void OnPause () {if (null! = Msoundpool) {msoundpool.unload (Msoundid) ; Msoundpool.release (); msoundpool = null;} Maudiomanager.setspeakerphoneon (false); maudiomanager.unloadsoundeffects (); Super.onpause ();}

Mediarecorder is used for recording.

To turn on recording:

private static final String Mfilename = Environment.getexternalstoragedirectory (). GetAbsolutePath () + "/ audiorecordtest.3gp ";p rivate void Startrecording () {mrecorder = new Mediarecorder (); Mrecorder.setaudiosource ( MediaRecorder.AudioSource.MIC); Mrecorder.setoutputformat (MediaRecorder.OutputFormat.THREE_GPP); Mrecorder.setoutputfile (Mfilename); Mrecorder.setaudioencoder (MediaRecorder.AudioEncoder.AMR_NB); try { Mrecorder.prepare ();} catch (IOException e) {log.e (TAG, "couldn ' t prepare and start Mediarecorder");} Mrecorder.start ();}

To turn off recording:

private void stoprecording () {if (null! = Mrecorder) {mrecorder.stop (); Mrecorder.release (); mrecorder = null;}}

Method Description:

The Setaudiosource () method in Mediarecorder sets the sound source, which is generally passed into the mediarecorder.audiosource. Mic Specifies that the sound from the microphone is recorded.

Setoutputformat sets the format of the recorded audio file. (Note that you must set the encoding format before you set it, or you will throw an exception)

Setaudioencoder Setting the encoding format

setaudioencodingbitrate (int bitrate) set encoding bit rate

setaudiosamplingrate (int samplingrate) Set sample rate

Setoutputfile (String Path) to set the location where the audio file is saved

then prepare (), start () starts playing

Stop (), release () stops playing, frees resources



MediaPlayer

Android supports a limited number of simultaneous media player images that, if not released, will cause the ANR to be consumed in the system

Therefore, when the playback is complete, the Mediaplay.release () method is used to release the resource.


Download audio from a package source

Mediaplayerresourceplayer = Mediaplayer.create (this, r.raw.my_audio);

Download audio from a local file

MediaPlayer resourceplayer= mediaplayer.create (This, Uri.parse ("File:///sdcard/localfile.mp3"));

Download the audio from a single online resource

MediaPlayer resourceplayer= mediaplayer.create (This, Uri.parse (URL));

Add audio from a content provider
Mediaplayerresourceplayer = Mediaplayer.create (This,
Settings.System.DEFAULT_RINGTONE_URI);
You can also setdatasource methods
Mediaplayermediaplayer = new MediaPlayer ();
Mediaplayer.setdatasource ("/sdcard/123.mp3");
Mediaplayer.prepare ();

Common methods

Mediaplayer.start ()

Mediaplayer.stop ()

Mediaplayer.pause ()


Adjust the left and right channel volume 0~1 The floating point number 0 is the Silence 1 is the largest

Mediaplayer.setvolume (0.5f,0.5f)

Powerful screen Solid

Mediaplayer.setscreenonwhileplaying (True)

Play on the Loop

If (!mediaplayer.islooping ()) {

Mediaplayer.setlooping (TRUE);

}


Example code:

Playing music and shaking: MediaPlayer = new MediaPlayer (); vibrator = (Vibrator) getsystemservice (Vibrator_service); long[] pattern = {1000 ,};vibrator.vibrate, $, (pattern, 0); try {mediaplayer.setvolume (1.0f, 1.0f); Mediaplayer.setdatasource (This, Uri); Mediaplayer.setaudiostreamtype (audiomanager.stream_alarm); mediaplayer.setlooping (true); Mediaplayer.prepare (); Mediaplayer.start ();   } catch (Exception e) {  mediaplayer.release ();}

Play ringtone Ringstone:

Types include:

Ringtonemanager. Type_ringtone

Ringtonemanager. type_notification

Ringtonemanager. Type_alarm


Example:

Uri Ringtoneuri = Ringtonemanager.getdefaulturi (ringtonemanager.type_ringtone);p Layringtone ( Ringtonemanager.getringtone (Getapplicationcontext (), Ringtoneuri));//Shut off current Ringtone and play new oneprivate void Playringtone (Ringtone newringtone) {if (null! = Mcurrentringtone && mcurrentringtone.isplaying ())    Mcurrentringtone.stop (); mcurrentringtone = Newringtone;    if (null! = Newringtone) {   mcurrentringtone.play ();}    }



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.