There are two kinds of playback audio forms, the first one: MediaPlayer class; The second: Soundpool class
MediaPlayer MediaPlayer01;
MediaPlayer01 = Mediaplayer.create (Youactivity.this, r.raw.xxxx);
Mediaplayer01.start ();
There are many ways to introduce MP to play sound files online:
1. Use r.raw.x to play the files in the raw directory,
2. Use Setdatasource ("/sdcard/s.mp4"), but did not say if you want to use Setdatasource () such a way to play the raw directory Files (setdatasource ("/raw/s.mp4").
First, the MediaPlayer playback audio implementation steps:
1. Call Mediaplayer.create (context, R.raw.himi); Use the MediaPlayer class to invoke the Create method and pass in the resource audio file through the ID index to get the instance;
2. The resulting instance can call Mediaplayer.star ();
Simple, actually MediaPlayer still have a few construction methods, we are interested to try and realize, here is mainly simple to introduce basic, after all, simple and practical best!
Second, the SoundPlayer playback audio implementation steps:
1. New one instance; New Soundpool (4, Audiomanager.stream_music, 100); The first parameter is how many sound streams are allowed to play simultaneously, the 2nd parameter is the sound type, the third parameter is the quality of the sound;
2.loadId = soundpool.load (Context, R.raw.himi_ogg, 1);
3. Use the instance call play method to pass in the corresponding audio file ID!
Here are the pros and cons of the two playback forms:
There are some disadvantages to using MediaPlayer to play audio files:
For example: High resource consumption, long delay time, multi-audio playback is not supported.
These shortcomings have determined that the use of MediaPlayer in certain situations will not be ideal, for example in game development where time accuracy is a relatively high requirement.
At the beginning I used to be ordinary mediaplayer way, but this method is not suitable for the game development, because the game plays a number of sound effects are often the thing, used MediaPlayer friends should know that it is not supported to play multiple sounds in real time, there will be more or less delay, And this delay is unbearable, especially in the fast continuous playback of the sound (such as the continuous push button), it will be very obvious, long time there will be a delay of 3-5 seconds, "using Mediaplayer.seekto () This method to solve the problem";
There are some problems with the use of Soundpool:
1. Soundpool can only request 1M of memory space, which means that we can only use some very short sound clips, rather than use it to play songs or game background music (background music can be considered using Jetplayer to play).
2. Soundpool provides pause and stop methods, but these methods are not recommended for easy use, because sometimes they may cause your program to end somehow. Some friends also reflect that they do not immediately stop playing the sound, but instead of playing the data in the buffer will stop, may play a second more.
3. The audio format is recommended in Ogg format. Using WAV audio files to store the game sound effects, after repeated testing, in the event of a short sound playback interval, there will be an abnormal shutdown situation (it is said that Soundpool currently only a 16bit WAV file has better support). Later, the issue was resolved by turning the file into Ogg format.
4. When playing audio with Soundpool, if the play function is called in the initialization, then there is no sound at all, not because there is no execution, but Soundpool needs a preparation time! 囧 Of course, this preparation time is also very short, will not affect the use, but the program runs on the play will be no sound, so I put soundpool play in the key processing, note 4 where
Probably after reading the pros and cons explanation, then look at my code notes where:
Note 1:
Here I define a HashMap, this is a hash table, if you do not know this class, it is recommended that Baidu Google Learning, it and Hashtable very common, it is the main difference between the two: HashMap different steps, null key value, high efficiency; Hashtable synchronous, non-null key value, the efficiency is slightly low, but in J2ME does not support HashMap, because I do not support null key value, so in me can only use Hashtable, cough, to the point, I use hashmap here mainly to deposit multiple audio ID, You can play multiple audio at the same time.
As described above, Soundpool can support multiple simultaneous audio playback, and this method is called when Soundpool is played (note 3) soundpool.play (LoadId, Currentvol, Currentvol, 1, 0, 1f); The first parameter refers to the previous Loadid! is obtained by means of soundpool.load (context, R.raw.himi_ogg, 1);
What's more to note is that the definition of HASHMAP must be defined as this form Hashmap<integer, integer> HM = new Hash<integer, Integer> Declaring this hash table is a hash table where both the key and the Volue value are integers! Why do this, because if you are simply defined as HashMap HM =new HASHMAP (), then when you play, that is, the note 4 method here the first ID parameter use Hashmap.get () This method will always appear the wrong hint!
"Soundpool can only apply 1M of memory space, which means we can only use some very short sound clips" Why only a few very short sound?
Everyone still look at the first parameter of the Note 4 method, where the incoming ID type is an int value, then this int corresponds to the audio ID returned by the load () method, and this ID will be larger and smaller due to the size of the audio file, so once our audio file exceeds the int maximum value, Then a memory error exception is reported. So why use Soundpool only to play some short audio This is the reason for it. Of course, why the OS is so defined I can not verify and explain.
Note 4: Explanation of parameters in this method
The first parameter is the audio corresponding ID that I returned through the Soundpool.load () method, the second third parameter represents the left and right channel size, the fourth parameter is the priority, the fifth parameter is the number of cycles, and the last is the playback rate (1.0 = Normal playback, range 0.5 to 2.0)
NOTE 2:
Here is an audio manager that can be adjusted to the volume size via media services. Here to emphasize, adjust the audio is to use this audio manager call Setstreamvolume () to adjust the way, instead of mediaplayer.setvolue (int leftvolume,int rightvolume); The two parameters of this method are also adjusted to the left and right channels instead of adjusting the sound size.
Well, for this we are in the game development in the end need to use what to do the analysis, summary is soundpool suitable to do special effects sound, actually play background music I feel or with MediaPlayer better, of course, with what all see everybody likes and choose! The following items are attached: (Project 10+MB because Res audio files are included)
Someone asked how to know that a song played, then here to say:
playbackcompleted Status: The file is played properly, and the loop is not set to enter the state, and will trigger the Oncompletionlistener oncompletion () method. You can now call the start () method to play back the file from the beginning, or stop () MediaPlayer, or you can Seekto () to reposition the playback position.
Note: 1, do not forget the binding operation! Mp.setoncompletionlistener (this);
2. If you set the loop to play mp.setlooping (true); , then you will never hear the status of playback complete!!!! Be sure to pay attention here!
Audio and video playback in ndroid the first thing we think about is the MediaPlayer class, which provides methods for playing, pausing, stopping, and repeating playback. This class is located under the Android.media package, see the API documentation. In fact, in addition to this class there is a music playback class that is Soundpool, these two classes have different analysis for everyone to understand
MediaPlayer:
This class is suitable for playing large files, which should be stored on an SD card rather than in a resource file, and this class can only play one audio file at a time.
This type of usage is as follows:
1. Play from the resource file
MediaPlayer player = new mediaplayer.create (this,r.raw.test);
Player.stare ();
2. Playback from File system
MediaPlayer player = new MediaPlayer ();
String Path = "/sdcard/test.mp3";
Player.setdatasource (path);
Player.prepare ();
Player.start ();
3. Play from the network
(1) by means of a URI:
String path= "Http://**************.mp3"; Here's a network address for a song.
Uri uri = uri.parse (path);
MediaPlayer player = new mediaplayer.create (This,uri);
Player.start ();
(2) How to set up the data source:
MediaPlayer player = new mediaplayer.create ();
String path= "Http://**************.mp3"; Here's a network address for a song.
Player.setdatasource (path);
Player.prepare ();
Player.start ();
Soundpool:
This type of feature is low-latency playback, suitable for playing real-time audio to play multiple sounds at the same time, such as the explosion of bombs in the game and other small resources files, this kind of audio is more suitable to be placed in the resource folder Res/raw and the program into the APK file.
Use the following:
Soundpool Soundpool = new Soundpool (4, Audiomanager.stream_music, 100);
Hashmap<integer, integer> soundpoolmap = new Hashmap<integer, integer> ();
Soundpoolmap.put (1, Soundpool.load (this, r.raw.dingdong1, 1));
Soundpoolmap.put (2, Soundpool.load (this, r.raw.dingdong2, 2));
public void PlaySound (int sound, int loop) {
Audiomanager mgr = (audiomanager) this.getsystemservice (Context.audio_service);
float streamvolumecurrent = Mgr.getstreamvolume (Audiomanager.stream_music);
float Streamvolumemax = Mgr.getstreammaxvolume (Audiomanager.stream_music);
float volume = Streamvolumecurrent/streamvolumemax;
Soundpool.play (Soundpoolmap.get (sound), volume, volume, 1, loop, 1f);
Parameters: 1, Map value 2, current volume 3, Maximum volume 4, priority 5, replay count 6, playback speed
}
This.playsound (1, 0);
Package com.robert.sound; Import Java.util.HashMap; Import Android.content.Context; Import Android.graphics.Canvas; Import Android.graphics.Color; Import Android.graphics.Paint; Import Android.media.AudioManager; Import Android.media.MediaPlayer; Import Android.media.SoundPool; Import android.view.KeyEvent; Import android.view.MotionEvent; Import Android.view.SurfaceHolder; Import Android.view.SurfaceView; Import Android.view.SurfaceHolder.Callback; public class Mysurfaceview extends Surfaceview implements Callback, Runnable {private Thread th; Private Surfaceholder SFH; Private Canvas canvas; Private MediaPlayer player; private paint paint; Private Boolean on = true; private int Currentvol, Maxvol; Private Audiomanager AM; Private Hashmap<integer, integer> soundpoolmap;//notes 1 private int loadId; Private Soundpool Soundpool; Public Mysurfaceview (Context COntext) {super (context); The Get audio service is then strongly turned into an audio manager, which is conveniently used to control the volume size with AM = (Audiomanager) mainactivity.instance. Getsystemserv Ice (Context.audio_service); Maxvol = Am.getstreammaxvolume (Audiomanager.stream_music); Get maximum volume value (15 Max!.). not 100! ) SFH = This.getholder (); Sfh.addcallback (this); th = new Thread (this); This.setkeepscreenon (TRUE); Setfocusable (TRUE); Paint = new paint (); Paint.setantialias (TRUE); MediaPlayer initialization player = mediaplayer.create (context, R.raw.himi); Player.setlooping (TRUE);//Set the initialization of the loop playback//soundpool soundpool = new Soundpool (4, Audiomanager.stream_mu SIC, 100); Soundpoolmap = new Hashmap<integer, integer> (); Soundpoolmap.put (1, Soundpool.load (Mainactivity.content, R.raw.himi_ogg, 1)); LoadId = soundpool.load (Context, R.raw.himI_ogg, 1); The last parameter of the load () method he identifies the preferred sound. There is no effect at this time. Used also just for the future compatibility value. } public void surfacecreated (Surfaceholder holder) {/* * Android OS, if you go to press the Adjust Volume button on your phone, there are two cases * One is to adjust the phone's own ringtone volume, one is to adjust the game, software, music playback volume * When we are in the game, always want to adjust the volume of the game and not the phone's ringtone volume, * But the annoying problem comes again, I am in the development of the Now, only the game has the sound in the playing time *, you can adjust the volume of the game, or the volume of the phone, there is no way to let the phone as long as the game is running the state of the game only adjust the volume? Try this piece of code! */MainActivity.instance.setVolumeControlStream (audiomanager.stream_music); Set the volume to the media volume, when the pause playback, adjust the volume will no longer default to adjust the ringtone volume, Wahaha player.start (); Th.start (); } public void Draw () {canvas = Sfh.lockcanvas (); Canvas.drawcolor (Color.White); Paint.setcolor (color.red); Canvas.drawtext ("Current Volume:" + Currentvol, +, +, paint); Canvas.drawtext ("Current playing time" + player.getcurrentposition () + "millisecond", +, (+), paint); Canvas.drawtext ("Arrow key middle button toggle Pause/Start", [+], paint); Canvas.drawtext ("Arrow key ← Fast rewind 5 Seconds", [] Canvas.drawtext ("direction key → Key fast forward 5 seconds", "the", "the", the paint); Canvas.drawtext ("Arrow key ↑ key to increase the volume", +, +/--); Canvas.drawtext ("Arrow key ↓ Key to decrease Volume", (+), (+), paint); Sfh.unlockcanvasandpost (canvas); private void Logic () {Currentvol = Am.getstreamvolume (audiomanager.stream_music);//continuously gets the current volume value } @Override public boolean onKeyDown (int key, KeyEvent event) {if (key = = Keyevent.keycode_dpad _center) {on =! On; if (on = = False) Player.pause (); else Player.start (); } else if (key = = keyevent.keycode_dpad_up) {//button This should be right, but since it is currently in landscape mode, the following is the same player.seekto (Player.getcurr Entposition () + 5000); } else if (key = = Keyevent.keycode_dpad_down) {if (Player.getcurrentposition () < 5000) { Player.seekto (0); } else {Player.seekto (player.getcurrentposition ()-5000); }} else if (key = = Keyevent.keycode_dpad_left) {Currentvol + = 1; if (Currentvol > Maxvol) {currentvol = 100; } am.setstreamvolume (Audiomanager.stream_music, currentvol,//notes 2 audiomanager.flag_ Play_sound); } else if (key = = Keyevent.keycode_dpad_right) {Currentvol-= 1; if (currentvol <= 0) {currentvol = 0; } am.setstreamvolume (Audiomanager.stream_music, Currentvol, audiomanager.flag_play_s Ound); } soundpool.play (LoadId, Currentvol, Currentvol, 1, 0, 1f);//Note 3//Soundpool.play (Soundpoolmap.get (1) , Currentvol, Currentvol, 1, 0, 1f);//Note 4//soundpool.pause (1);//Pause SoundpoOl ' Voice return Super.onkeydown (key, event); } @Override public boolean ontouchevent (Motionevent event) {return true; } public void Run () {//TODO auto-generated method stub while (true) {Draw ( ); Logic (); try {thread.sleep (100); } catch (Exception ex) {}}} public void Surfacechanged (Surfaceholder holder, I NT format, int width, int height) {} public void surfacedestroyed (Surfaceholder holder) { } }
Android Dev Play sound file