0

In my android game, there are 36 falling balls. When a ball touches the ground a sound is played. The sound is very small, only 0.3 sec. I am using soundpool class to play it. It may happen in the game that all 36 balls fall in quick succession. Playing the sound so many times may block the UI thread. Is it advisable to play sound on separate thread ?

user3293494
  • 609
  • 1
  • 9
  • 21

1 Answers1

1

Yes! You should play the sound on a a separate thread. Check the solution provided to a similar question here

Community
  • 1
  • 1
Nana Ghartey
  • 7,901
  • 1
  • 24
  • 26
  • Wont spawning a new thread for every play of sound will affect performance/animation ? – user3293494 Apr 07 '14 at 12:05
  • Are you using OpenGL or Canvas? In OpenGL, the GLSurfaceView creates the UI thread and a Renderer thread. Renderer.onDrawFrame() should be doing a minimum of work to get the highest FPS. Sound, Music and the game logic(AI, physics etc) don't need to run every frame, so you can put those in another thread. You don't have to "spawn" a new thread on each play of a sound. – Nana Ghartey Apr 07 '14 at 17:31
  • thread.start() can be used once only, so to replay a sound in non UI thread, one has to spawn a new thread – user3293494 Apr 07 '14 at 19:40
  • Ok.I get you. You start the thread to play the sound and "stop" it when the sound has completed playing. This is ok if you aren't playing in quick successions but in your case it isn't advisable. What I meant was - start the thread once and play/stop the sound in it's run() method. Then "stop" the thread when the game is over/restarted – Nana Ghartey Apr 07 '14 at 22:50
  • when run method has executed the thread dies automatically..right? so how it can be re-used for playing the sound again and again a s per user input. – user3293494 Apr 08 '14 at 09:45
  • It doesn't die automatically. You stop it manually. Eg. run(){ while(!stopThread){ if(!soundPlayed) playSound() }} – Nana Ghartey Apr 08 '14 at 16:22
  • you are running an infinite loop in thread, that will also consume resources and time. – user3293494 Apr 08 '14 at 19:52
  • Yes, it'll but it can be paused by setting stopThread to false after playing sound. Unfortunately, it's not possible to create a thread and reuse it. If it were, you could have rerun the same thread for each sound play. You can use a thread pool too – Nana Ghartey Apr 08 '14 at 23:45
  • @NanaGhartey, doesn't SoundPool manage threads itself? I mean, I'm not spawning my own thread for my SoundPool objects and when I debug my code I can see various SoundPool threads listed. Therefore, unless I'm misunderstanding, what advantage do we get by calling our SoundPool object from a self-spawned thread? :-/ – Zippy Jan 22 '16 at 23:30
  • SoundPool uses a Handler, if you look at the source code, there is an inner class called EventHandler which inherits from Handler. I guess Soundpool doesn´t need to be in an extra thread. – Opiatefuchs May 13 '17 at 06:55