2

As many developers know, using AVAudioPlayer for playing sound in games can result in jerky animation/movement, because of a tiny delay each time a sound is played.

I used to overcome this in Objective-C, by using OpenAL through a wrapper class (also in Obj-C).

I now use Swift for all new projects, but I can't figure out how to use my wrapper class from Swift. I can import the class (through a bridging header), but when I need to create ALCdevice and ALCcontext objects in my Swift file, Xcode won't accept it.

Does anyone have or know of a working example of playing a sound using OpenAL from Swift? Or maybe sound without lag can be achieved in some other way in Swift?

Richard G. Nielsen
  • 1,221
  • 10
  • 13
  • "but when I need to create ALCdevice and ALCcontext objects in my Swift file, Xcode won't accept it." What does _that_ mean? Maybe that's what you should concentrate on. Code is just code, so if you can do this in Objective-C, you can talk to your Objective-C wrapper from Swift. – matt May 09 '15 at 02:35
  • The problem is that ALCdevice and ALCcontext are C++ classes (I think), and this is something Swift can't handle. – Richard G. Nielsen May 09 '15 at 09:56
  • What Swift can't handle is creation and passing of pointers to C functions. But that's fine; you just leave that part of your code in Objective-C, as described here: http://stackoverflow.com/questions/25057161/how-to-use-the-coreaudio-api-in-swift That is what I meant when I said "you can talk to your Objective-C wrapper from Swift" – matt May 09 '15 at 13:58
  • And see also my book: http://www.apeth.com/swiftBook/apa.html#_c_functions – matt May 09 '15 at 13:58

1 Answers1

2

I've ran to a delay-type problem once, I hope your problem is the same one I've encountered.

In my situation, I was using Sprite-Kit to play my sounds, using SKAction.playSoundFileNamed:. It would always lag half a second behind where I wanted it to play.

This is because it takes time to allocate memory for each SKAction call. To solve this, store the sound action in a variable so you can reuse the sound later without instantiating new objects. It saved me from the delay. This technique would probably work for AVAudioPlayer too.

Kelvin Lau
  • 6,373
  • 6
  • 34
  • 57
  • Unfortunately, this isn't the same problem as I'm having. Imagine some image moving smoothly across the screen. I then play a sound using AVAudioPlayer, and the movement jerks a little, just a little tug, almost unnoticable, but if I play lots of little sounds, the movement is no longer smooth. – Richard G. Nielsen May 09 '15 at 10:08
  • Hmm. Could you tell me how you are updating the sprite's movements? Are you possibly offsetting the sprite by a fixed amount and relying on `update` to displace the sprite? – Kelvin Lau May 09 '15 at 13:34