I am trying to initialize and play an AVAudioPlayer
from a URL that contains an M4A file. The file is below:
Here is the code I am using to initialize said AVAudioPlayer:
var player: AVAudioPlayer!
let preview = "https://audio-ssl.itunes.apple.com/apple-assets-us-std-000001/AudioPreview123/v4/e8/04/59/e80459fb-9429-3323-4f43-ce12d5df1be5/mzaf_5785529815715338950.plus.aac.p.m4a"
func loadAudio() {
do {
self.player = try AVAudioPlayer(contentsOf: URL(string: preview!)!, fileTypeHint: AVFileType.m4a.rawValue)
self.player.play()
} catch let error {
print("Error:", error.localizedDescription)
}
}
@IBAction func buttonPressed(_ sender: Any) {
loadAudio()
}
When pressing the button associated with that IBAction
named buttonPressed(sender:)
, I am receiving the following error:
The operation couldn’t be completed. (OSStatus error 2003334207.)
I have tried troubleshooting with similar questions regarding this error, but none seem to resolve my issue.
Edit:
I tried doing something similar with AVPlayer
and, while it didn't throw an error, the file simply didn't play. Here is some sample code:
var avPlayer: AVPlayer!
let preview = "https://audio-ssl.itunes.apple.com/apple-assets-us-std-000001/AudioPreview123/v4/e8/04/59/e80459fb-9429-3323-4f43-ce12d5df1be5/mzaf_5785529815715338950.plus.aac.p.m4a"
func loadAudio() {
if let url = NSURL(string: preview!) {
self.avPlayer = AVPlayer(url: url as URL)
self.avPlayer.volume = 1.0
self.avPlayer.play()
}
}
@IBAction func buttonPressed(_ sender: Any) {
loadAudio()
}
I feel like an idiot. My phone was on "silent mode" when running this code. Per this answer I needed to add
do {
try AVAudioSession.sharedInstance().setCategory(AVAudioSession.Category.playback)
}
catch {
// report for an error
}
before actually plying from the AVPlayer.
The reason this problem hadn't crossed my mind was because when looking at the music manager in my iPhone's Control Center, there was no indication of audio being played. Just because audio is being played doesn't mean that playback controls are being handled by the device's Control Center.