0
votes

I am currently testing the SpriteKit positional audio implementation and found myself stuck after switching from loading a mp3 file to buffering the file.

The file buffer is loading correctly but I lost the positional audio effect of SpriteKit and it appears that I can't change the position of the audio source by changing the parent SKSpriteNode (like I used to).

Here is my code and I would be very happy to hear your thoughts:

import SpriteKit
import AVFoundation

class GameScene: SKScene {

var audioFilePlayer = AVAudioPlayerNode()
var mainMixer = AVAudioMixerNode()
var bufferFormat = AVAudioPCMBuffer()

override func didMove(to view: SKView) {

   let player = SKSpriteNode(imageNamed: "player")
   player.position =  CGPoint(x:0,y:0)
   scene?.addChild(player)

   let sprite = SKSpriteNode(imageNamed: audioSourceImage)
   sprite.position = CGPoint(x:10,y:0)
   
   // setup nodes
   var backgroundMusic = SKAudioNode()
   sprite.addChild(backgroundMusic)
   player.addChild(sprite)
   // setup audio buffer and link to audioEngine
   let url = Bundle.main.url(forResource: "audioSourceMono", withExtension: "m4a")
   let file = try! AVAudioFile(forReading: url!)
   do {
       let audioFormat = file.processingFormat
       let audioFrameCount = UInt32(file.length)
       guard let audioFileBuffer = AVAudioPCMBuffer(pcmFormat: audioFormat, frameCapacity: audioFrameCount) else{ return }
       self.bufferFormat = audioFileBuffer
       try file.read(into: audioFileBuffer)
       
       //get scene main mixer and connect audioPlayer to mixer
       scene!.audioEngine.attach(self.audioFilePlayer)
       let mainMixer = scene!.audioEngine.mainMixerNode
       backgroundMusic.avAudioNode = audioFilePlayer
       scene!.audioEngine.connect(backgroundMusic.avAudioNode!, to: mainMixer, format: audioFileBuffer.format)
                            
       try audioEngine.start()

       audioFilePlayer.scheduleBuffer(audioFileBuffer, completionHandler: nil)
       audioFilePlayer.play()
   } catch {
       print(error)
   }

   // enable positional audio
   backgroundMusic.isUserInteractionEnabled = true
   backgroundMusic.isPositional = true

}