watchOS play audio when screen sleeping

Hi

I have written a watchOS that plays audio out the speaker using files stored locally and this works fine but when you lower your hand and the screen ‘sleeps’ the audio stops playing. If you raise your wrist again it does finishes playing the audio. I have tried enabling as suggested by Apple with “Under the Capabilities tab, set the Background Modes” but am I missing something or is it not possible to let an audio complete.


Andrew

It has been suggested to post some of my code. The first snippet below only gives a warning that "longForm" is depreciated, so I dont know what to do and this is commented out.


  let session = AVAudioSession.sharedInstance()
  AVAudioSession.RouteSharingPolicy.longFormAudio
  do {
  // try AVAudioSession.session.RouteSharingPolicy.longFormAudio
  try session.setCategory(AVAudioSession.Category.playback,
  mode: .default,
  policy: .longForm,
  options: [])
  } catch let error {
  fatalError("*** Unable to set up the audio session: \(error.localizedDescription) ***")
  }



This is the code I am using and it plays the .aiff files without problems, except the sound stop playing when wrist lowered.


  let pathOne = Bundle.main.path(forResource: audioOneFile, ofType: ".aiff")!
  let urlOne = URL(fileURLWithPath: pathOne) // = 1
  let pathTwo = Bundle.main.path(forResource: audioTwoFile, ofType: ".aiff")!
  let urlTwo = URL(fileURLWithPath: pathTwo) // = 2

  do {
  self.audioOnePlay = try AVAudioPlayer(contentsOf: urlOne)
  self.audioTwoPlay = try AVAudioPlayer(contentsOf: urlTwo)
  } catch {
  // couldn't load file :(
  assertionFailure("Failed creating audio player: \(error).")
  }

  DispatchQueue.main.async { // Start by speaking first phrase
  self.audioOnePlay.play()
  // These wait until the PRVIOUS phrase has been played
  DispatchQueue.main.asyncAfter(deadline: .now() + oneDurationNumber) {
  self.audioTwoPlay.play()
  } // Audio Two
  }


Any help would be gratefully received.


Andrew

It looks like .longFormAudio and .longFormVideo have replaced .longForm

It might be worth trying the appropriate one to see if that makes a difference.

Hi jlilest002


I tried your suggestion and another line of code :- AVAudioSession.RouteSharingPolicy.longFormAudio but unfortunately it didn't work. I am not very experienced in programming so maybe I am inserting this code in the wrong place, it's just before the code to define the audio path and "try AVAudioPlayer(contentsOf: urlPath)"


  let session = AVAudioSession.sharedInstance()
  // AVAudioSession.RouteSharingPolicy.longFormAudio
  do {
  // try AVAudioSession.session.RouteSharingPolicy.longFormAudio
  try session.setCategory(AVAudioSession.Category.playback,
  mode: .default,
  policy: .longFormAudio,
  options: [])
  } catch let error {
  fatalError("*** Unable to set up the audio session: \(error.localizedDescription) ***")
  }


Andrew

watchOS play audio when screen sleeping
 
 
Q