Audio Processing in Android ------ SoundPool, MediaRecorder, MediaPlayer, and RingStone Summary

Source: Internet
Author: User

With Soundpool, you can play a few short sounds with high response speed requirements, such as bursts in the game,

Mediaplayer is suitable for long playback. MediaRecorder is mainly used for recording.


The SoundPool uses an independent thread to load music files and does not block the operations of the main UI thread.

However, if the audio file is too large to be loaded, we may have serious consequences when calling the play method,

Here, the AndroidSDK provides a SoundPool. OnLoadCompleteListener class to help us understand whether media files are loaded completely,

We can obtain the onLoadComplete (SoundPool soundPool, int sampleId, int status) method by reload.

SampleId

The sample ID of the sound loaded.

Status

The status of the load operation (0 = success)


From the onLoadComplete method, we can see that this class has many parameters,

For example, similar to the id, SoundPool can process multiple media initialization at a time during load and put it into the memory,

The efficiency is much higher than MediaPlayer.


The SoundPool class supports playing multiple sound effects at the same time, which is very necessary for the game,

The MediaPlayer class synchronizes the playback of only one file.

Create:

Public SoundPool (int maxStream, intstreamType, 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 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.

Generally, multiple voices are put in HashMap, for example
SoundPool = new SoundPool (4, AudioManager. STREAM_MUSIC, 100 );
SoundPoolMap = new HashMap ();
SoundPoolMap. put (1, soundPool. load (this, R. raw. dingdong, 1 ));

Load:
Int load (Context context, intresId, int priority) // load data from the APK Resource
Int load (FileDescriptor fd, long offset, long length, intpriority) // 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.


Play:
Play (int soundID, float leftVolume, float rightVolume, int priority, int loop, float rate ),

LeftVolume and rightVolume indicate the Left and Right volume, priority indicates the priority, loop indicates the number of cycles, and rate indicates the rate,

For example
// The lowest speed is 0.5. The highest speed is, indicating the normal speed.
Sp. play (soundId, 1, 1, 1, 0, 1.0f );


You can use the pause (int streamID) method to stop the streaming,

Here, both streamID and soundID specify the total number in the first parameter for constructing the SoundPool class, and id starts from 0.

Get audioManager object

AudioManager mAudioManager = (AudioManager) getSystemService (AUDIO_SERVICE);

Playing Sound Effects

MAudioManager. playSoundEffect (AudioManager.FX_KEY_CLICK);

Generally, the OnResume and OnStop methods of AudioManager must be processed 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.

Enable recording:

private static final String mFileName = Environment.getExternalStorageDirectory().getAbsolutePath()+ "/audiorecordtest.3gp";private 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();}

Disable recording:

private void stopRecording() {if (null != mRecorder) {mRecorder.stop();mRecorder.release();mRecorder = null;}}

Method description:

The setAudioSource () method in MediaRecorder sets the sound source. Generally, MediaRecorder. AudioSource is passed in.MICSpecifies the recording sound from the microphone.

SetOutputFormat sets the format of the recorded audio file. (Note that you must set the encoding format before setting it. Otherwise, an exception is thrown)

SetAudioEncoder: Set the encoding format

SetAudioEncodingBitRate (int bitRate) sets the encoding bit rate

SetAudioSamplingRate (int samplingRate) sets the sampling rate

SetOutputFile (String path) is used to set the location for saving audio files.

Then, prepare () and start () start playing.

Stop (), release () stop playing, release resources



MediaPlayer

Android supports synchronization of Media Player images with a limited amount of data. If you do not release them, it will cause ANR

Therefore, when the playback is complete, use the mediaPlay. release () method to publish the relevant data source.


// Adds audio streams from a package

MediaPlayerresourcePlayer = MediaPlayer. create (this, R. raw. my_audio );

// Adds audio streams to a local file

MediaPlayer resourcePlayer = MediaPlayer. create (this, Uri. parse ("file: // sdcard/localfile= "));

// Adds audio streams from a local resource

MediaPlayer resourcePlayer = MediaPlayer. create (this, Uri. parse (URL ));

// Adds audio streams from a Content Provider
MediaPlayerresourcePlayer = MediaPlayer. create (this,
Settings. System. DEFAULT_RINGTONE_URI );
// You can also use the setDataSource method.
MediaPlayermediaPlayer = new MediaPlayer ();
MediaPlayer. setDataSource ("/sdcard/123.mp3 ");
MediaPlayer. prepare ();

Common Methods

MediaPlayer. start ()

MediaPlayer. stop ()

MediaPlayer. pause ()


// Adjust the volume between the left and right channels to 0 ~ The floating point number between 1 and 0 is the maximum value of audio 1.

MediaPlayer. setVolume (0.5f, 0.5f)

// The Ghost screen is always on

MediaPlayer. setScreenOnWhilePlaying (true)

// Stream playback

If (! MediaPlayer. isLooping ()){

MediaPlayer. setLooping (true );

}


Sample Code:

Play audio and earthquake: mediaPlayer = new MediaPlayer (); vibrator = (Vibrator) getSystemService (VIBRATOR_SERVICE); long [] pattern = {1000,200,200,200}; 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 ();}

Playing ringtone RingStone:

Types include:

RingtoneManager.TYPE_RINGTONE

RingtoneManager.TYPE_NOTIFICATION

RingtoneManager.TYPE_ALARM


Example:

Uri ringtoneUri = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_RINGTONE);playRingtone(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();    }}



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.