Control audio on lock screen using AVAudioPlayer - ios

I have background mode active for audio and I use this method to play files, but I can't control them when the screen is locked.
func loadSound(resource: String, soundExtension: String) {
guard let url = Bundle.main.url(forResource: resource, withExtension: soundExtension) else {
return
}
UIApplication.shared.beginReceivingRemoteControlEvents()
do {
try AVAudioSession.sharedInstance().setCategory(AVAudioSessionCategoryPlayback)
try AVAudioSession.sharedInstance().setActive(true)
player = try AVAudioPlayer(contentsOf: url, fileTypeHint: AVFileType.mp3.rawValue)
} catch let error {
print(error.localizedDescription)
}
}

For someone with the same problem, call this method in the question method
fileprivate let remoteCommandCenter = MPRemoteCommandCenter.shared()
func activateControlCenterCommands() {
remoteCommandCenter.playCommand.addTarget(self, action: #selector(handlePlayCommandEvent(_:)))
remoteCommandCenter.pauseCommand.addTarget(self, action: #selector(handlePauseCommandEvent(_:)))
remoteCommandCenter.playCommand.isEnabled = true
remoteCommandCenter.pauseCommand.isEnabled = true
}

Related

Ok so I'm new to Swift. I've been trying to make an audio player and the code just gives me this error. What can I do?

import UIKit
import AVFoundation
class AVAudioPlayer : NSObject {
}
class ViewController: UIViewController {
#IBAction func keyPressed(_ sender: UIButton) {
}
override func viewDidLoad() {
super.viewDidLoad()
}
}
func playSound() {
let player: AVAudioPlayer?
guard let sound = Bundle.main.url(forResource: "C", withExtension: "wav") else { return }
do {
try AVAudioSession.sharedInstance().setCategory(.playback, mode: .default)
try AVAudioSession.sharedInstance().setActive(true)
player = try AVAudioPlayer(contentsOfURL: sound, fileTypeHint: AVFileType.wav.rawValue)
guard let player = player else { return }
func play() -> Bool {}
} catch let error {
print(error.localizedDescription)
}
Xcode gives me an error in this line player = try AVAudioPlayer(contentsOfURL: sound, fileTypeHint: AVFileType.wav.rawValue) saying that Argument passed to call that takes no arguments
Replace '(contentsOfURL: sound, fileTypeHint: AVFileType.wav.rawValue)' with '' and when I try to fix it, it gives me this error: Cannot assign value of type 'AVAudioPlayer.Type' to type 'AVAudioPlayer'. Can somebody help me? PS sorry for bold, Stack wouldn't let me post because it had "too much code in it".
After the help from Sweeper, my code looks like this:
import AVFoundation
class ViewController: UIViewController {
var player: AVAudioPlayer?
#IBAction func keyPressed(_ sender: UIButton) {
}
override func viewDidLoad() {
super.viewDidLoad()
}
}
func playSound() {
guard let sound = Bundle.main.url(forResource: "C", withExtension: "wav") else { return }
do {
try AVAudioSession.sharedInstance().setCategory(.playback, mode: .default)
try AVAudioSession.sharedInstance().setActive(true)
player = try AVAudioPlayer
guard let player = player else { return }
func play() -> Bool {}
} catch let error {
print(error.localizedDescription)
}
As I was saying in the comments, now it gives me this error: Use of unresolved identifier 'player'
You need to provide init(contentsOf:) throws method to initialize the player. Here is the code you need:
class ViewController: UIViewController {
var player: AVAudioPlayer?
func playSound() {
guard let sound = Bundle.main.url(forResource: "C", withExtension: "wav") else { return }
do {
try AVAudioSession.sharedInstance().setCategory(.playback, mode: .default)
try AVAudioSession.sharedInstance().setActive(true)
player = try AVAudioPlayer(contentsOf: sound)
player?.play()
} catch let error {
print(error.localizedDescription)
}
}
}

Multiple Audio Files In One ViewController With Button

Want to play multiple audio files in the same ViewController. When a user clicks on Button1 the file1.mp3 should be loaded into ViewController and when user hit play same should play and for button2 file2.mp3 should load and play.
I know how to do this for a single file but for multiple files I have to create ViewController again and again which is so hard. This is my code for single file
#IBAction func buttonPressed(_ sender: UIButton) {
if player.isPlaying {
player.stop()
sender.setImage(UIImage(named:"play.png"),for: .normal)
} else {
player.delegate = self
player.play()
player.numberOfLoops = 107
sender.setImage(UIImage(named:"pause.png"),for: .normal)
}
}
do {
let audioPlayer = Bundle.main.path(forResource: "chalisa", ofType: "mp3")
try player = AVAudioPlayer(contentsOf: NSURL(fileURLWithPath: audioPlayer!) as URL)
}catch {
//ERROR
}
You can use Tableview List all songs Name and Play Button use to Multiple audio files use in one viewcontroller
import AVFoundation
//MARK:- Variable Declaration
var player: AVAudioPlayer?
func playMusic() {
guard let url = Bundle.main.url(forResource: "chalisa", withExtension: "mp3") else { return }
do {
try AVAudioSession.sharedInstance().setCategory(.playback, mode: .default)
try AVAudioSession.sharedInstance().setActive(true)
player = try AVAudioPlayer(contentsOf: url, fileTypeHint: AVFileType.mp3.rawValue)
/* iOS 10 and earlier require the following line:
player = try AVAudioPlayer(contentsOf: url, fileTypeHint: AVFileTypeMPEGLayer3) */
guard let player = player else { return }
player.play()
} catch let error {
print(error.localizedDescription)
}
}

Using a UITapGestureRecognizer to play/pause audio

This seems like a fairly simple task, but have been trying for a while to figure it out... I have set up a UITapGestureRecognizer to play an audio file from the bundle. That works well, but I would like to have the user be able to tap the item again and have the audio stop. Basically have the ability to start and replay the audio by tapping the object with single taps.
#IBAction func page1Tapped(_ sender: UITapGestureRecognizer) {
let url:URL = Bundle.main.url(forResource: "Opening Solo", withExtension: "mp3")!
do {
audioPlayer = try AVAudioPlayer(contentsOf: url, fileTypeHint: nil)
} catch {
return
}
audioPlayer.prepareToPlay()
audioPlayer.play()
if audioPlayer.isPlaying {
audioPlayer.stop()
} else {
audioPlayer.play()
}
}
Here is the function that I have created. The audio only plays and just restarts at 0 with every tap at this point.
Any help is incredibly appreciated!!
This because every click creates a new re-assings the old instance , you can declare the player as instance variable
var audioPlayer:AVAudioPlayer?
and check it's value before assigning
if audioPlayer == nil
{
audioPlayer = try AVAudioPlayer(contentsOf: url, fileTypeHint: nil)
audioPlayer.play()
}
else
{
if audioPlayer.isPlaying {
audioPlayer.stop()
} else {
audioPlayer.play()
}
}

Swift 2 - AVAudioPlayer not playing audio

I'm trying to play a sound with an AVAudioPlayer, but it doesn't play. I tried both a device (iPhone 6s) and the simulator. I'm not getting any errors and it logs it played. When I set a breakpoint before audioPlayer.play() and step over it plays for a few seconds and stops then. My code:
let soundURL = NSBundle.mainBundle().URLForResource("test", withExtension: "mp3")
do {
try AVAudioSession.sharedInstance().setCategory(AVAudioSessionCategoryPlayback)
try AVAudioSession.sharedInstance().setActive(true)
if let soundURL = soundURL {
let audioPlayer = try AVAudioPlayer(contentsOfURL: soundURL)
audioPlayer.volume = 1
audioPlayer.delegate = self
audioPlayer.prepareToPlay()
print(audioPlayer.duration)
audioPlayer.play()
print("PLAYED")
}
}catch {
print("Error getting the audio file")
}
Here is an example that will work. I am not sure where, in relation to the rest of your code, you have the code that you've shown above. Make sure your device volume is not on silent and is turned up...
//declare these as instance variables
var AudioURL = NSURL(fileURLWithPath: NSBundle.mainBundle().pathForResource("FileName", ofType: "mp3")!)
var AudioPlayer = AVAudioPlayer()
//inside viewDidLoad establish your AVAudioSession and configure the AudioPlayer with the contents of URL
override func viewDidLoad() {
super.viewDidLoad()
do {
try AVAudioSession.sharedInstance().setCategory(AVAudioSessionCategoryPlayback)
//print("AVAudioSession Category Playback OK")
do {
try AVAudioSession.sharedInstance().setActive(true)
//print("AVAudioSession is Active")
} catch let error as NSError {
print(error.localizedDescription)
}
} catch let error as NSError {
print(error.localizedDescription)
}
do {
try AudioPlayer = AVAudioPlayer(contentsOfURL: AudioURL, fileTypeHint: nil)
} catch {
print("errorin do-try-catch")
}
}
//play audio
#IBAction func playAudio(sender: AnyObject){
AudioPlayer.play()
}

AVAudioPlayer produces lag despite prepareToPlay() in Swift

Playing a very short sound (~0.5s) produces a hiccup (like a lag) in my SpriteKit iOS game programmed in Swift. In other questions, I read that I should prepareToPlay() the sound, which I did.
I even used a variable (soundReady) to check if the sound is prepared before playing it. I also re-prepare the sound whenever it is finished playing (audioPlayerDidFinishPlaying()). Here are the relevant parts of the code:
class GameScene: SKScene, AVAudioPlayerDelegate {
var splashSound = NSURL()
var audioPlayer = AVAudioPlayer()
var soundReady = false
override func didMoveToView(view: SKView) {
let path = NSBundle.mainBundle().pathForResource("plopSound", ofType: "m4a")
splashSound = NSURL(fileURLWithPath: path)
audioPlayer = AVAudioPlayer(contentsOfURL: splashSound, error: nil)
audioPlayer.delegate = self
soundReady = audioPlayer.prepareToPlay()
}
func playSound(){
if(soundReady){
audioPlayer.play()
soundReady = false
}
}
func audioPlayerDidFinishPlaying(player: AVAudioPlayer!, successfully flag: Bool){
//Prepare to play after Sound finished playing
soundReady = audioPlayer.prepareToPlay()
}
}
I have no idea where I've gone wrong on this one. I feel like I have tried everything (including, but not limited to: only preparing once, preparing right after playing, not using a variable, but just prepareToPlay()).
Additional information:
The sound plays without delay.
How quickly the sound is played after the last finish does not seem to impact the lag.
I ran into this same problem and played the sound in the backgroundQueue.
This is a good example: https://stackoverflow.com/a/25070476/586204.
let qualityOfServiceClass = QOS_CLASS_BACKGROUND
let backgroundQueue = dispatch_get_global_queue(qualityOfServiceClass, 0)
dispatch_async(backgroundQueue, {
audioPlayer.play()
})
Just adding a Swift 3 version of the solution from #brilliantairic.
DispatchQueue.global().async {
audioPlayer.play()
}
When I called play multiple times it would cause bad access. I believe the player is being deallocated since this is not thread safe. I created a serial queue to alleviate this problem.
class SoundManager {
static let shared = SoundManager()
private init() {
try? AVAudioSession.sharedInstance().setCategory(AVAudioSessionCategoryPlayback)
try? AVAudioSession.sharedInstance().setActive(true)
}
private let serialQueue = DispatchQueue(label: "SoundQueue", qos: .userInitiated)
private var player: AVAudioPlayer?
static func play(_ sound: Sound) {
shared.play(sound)
}
func play(_ sound: Sound) {
guard let url = Bundle.main.url(forResource: sound.fileName, withExtension: "mp3")
else { return }
do {
try serialQueue.sync {
self.player = try AVAudioPlayer(contentsOf: url, fileTypeHint: AVFileTypeMPEGLayer3)
DispatchQueue.main.async {
self.player?.play()
}
}
} catch let error as NSError {
print("error: \(error.localizedDescription)")
}
}
}

Resources