I add a Quick look extension to my app to preview my custom file type. The Kodeco.com has a good starting point. I need to play a sound in this preview view controller. I use AVAudioPlayer()
like this:
class SoundPlayer {
var logger: Monitor = Monitor(.Mecordi)
var audioPlayer: AVAudioPlayer?
init(from soundURL: URL) {
do {
audioPlayer = try AVAudioPlayer(contentsOf: soundURL)
audioPlayer?.prepareToPlay()
} catch {
print("Error loading sound file: (error.localizedDescription)")
}
}
func playSound() {
audioPlayer?.play()
}
func stopSound() {
audioPlayer?.stop()
}
}
class PreviewViewController: UIViewController, QLPreviewingController {
var soundPlayer: SoundPlayer?
// @IBOutlet weak var previewView: PreviewView!
override func viewDidLoad() {
super.viewDidLoad()
}
@IBAction func playAction(_ sender: Any) {
let audioFileURL = Bundle.main.url(forResource: "sound", withExtension: "mp3")!
self.soundPlayer = SoundPlayer(from: audioFileURL)
self.soundPlayer?.playSound()
}
}
It works on simulator, but on device it raise following errors:
[AQClient] AQClient.cpp:692 Couldn't connect to com.apple.audio.AudioQueueServer; AudioQueue will not be usable
[default] AudioQueueNew is passing a serverPID of 0 to CheckRPCError!
[default] CheckRPCError: AudioQueueNew returned server mach error 0x10000003!
[default] FetchAndDeliverPendingCallbacks is passing a serverPID of 0 to CheckRPCError!
[default] AudioQueueDispose is passing a serverPID of 0 to CheckRPCError!
[default] CheckRPCError: FetchAndDeliverPendingCallbacks returned server mach error 0x10000003!
[UIKBFeedbackGenerator] <_UIKBFeedbackGenerator: 0x281e6a080>: Error, attempting to read ringer state with an invalid token.
By the way, if I use AVAudioEngine
it will play the sound on both simulator and device. But I need to solve it with AVAudioPlayer()
.