I have an app which needs to play audio in the background... Is this possible using Swift and SpriteKit with SKActions... Or is it possible another way..
A nudge in the right direction would be very helpful.
I have an app which needs to play audio in the background... Is this possible using Swift and SpriteKit with SKActions... Or is it possible another way..
A nudge in the right direction would be very helpful.
After trying out a few things I stumbled upon a reasonable solution. For playing music in a loop you can set up an SKAudioNode and set the AutoPlayedLoop = true. Then call the "play music" method in when Scene loads.
Now, if you want a sound effect you can use an SKAudioNode for that as well. I found that the sound effect started repeating and so to counteract that I simply created a play-stop sequence. Essentially, every time the sound effect was triggered it would run this sequence, hence, it only sounded once, as intended. There was a cut off to the sound effect however, so I created a simple colour shade method for about 1 second and added this to the sequence. Now the sequence produced was play-shade-stop. Every time the sound effect ran this sequence the dormant shade action would give it a 1 second lag and allow it to play fully and then it would stop as intended. Based on the sound effect you can use the dormant shade action to compensate as required, sometimes longer, sometimes shorter.
Well, here is the code. It's pretty straightforward and you don't need to create a whole AVPlayer class for it.
Furthermore, you can adjust the volume properties having all audio as AudioNodes, to create a good audio mix between the music in the background and the sound effects and also to pronounce certain other effects over others. Hope this helps.
By the way, you can't cast an SKAudioNode into an AVAudioNode, just to bare in mind.
SKAction
is really easy to use with sounds, but sometimes you might want to do more.In that case, you would want to use
AVAudioPlayer
instead of it.In order to not write your own "player", I suggest you to use an existing one. Here is one I've already used (SKTAudio) : https://github.com/raywenderlich/SKTUtils/blob/master/SKTUtils/SKTAudio.swift
Here is how to use it :
As you can see, you'll be able to either play short sound (as you might already have done with
SKAction
) and even background music that will play in loop as you're looking for.