iOS Swift: Sound not playing
You just need to move the declaration of your audioPlayer out of your method. Try like this:
Swift 3 or later
var audioPlayer = AVAudioPlayer()
func playSound() throws {
let url = Bundle.main.url(forResource: "doorbell", withExtension: "mp3")!
audioPlayer = try AVAudioPlayer(contentsOf: url)
audioPlayer.prepareToPlay()
audioPlayer.play()
}
do {
try playSound()
} catch {
print(error)
}
sound is playing in simulator but not on physical device
Double check the code you've posted is not falling into the catch block. You should see an error in the console if an error is produced.
do {
print("ran")
player = try AVAudioPlayer(contentsOf: url)
player?.play()
} catch let error {
print(error.localizedDescription)
}
You should also check the device is not on silent. To prevent this you can use the below that will always the play the audio as the audio sessions category will be set to .playback
do {
try AVAudioSession.sharedInstance().setCategory(.playback)
} catch let error {
print(error.localizedDescription)
}
AVAudioPlayer not playing audio Swift
UPDATE/SOLUTION:
So the problem was that audioPlayer would become deallocated before it would play the sound, to fix this I had to make it a property within the class instead of just creating an instance of it within the function. The updated code looks like this:
Optional reference within the property declarations of the class:
var audioPlayer : AVAudioPlayer?
The function that utilizes the audioPlayer:
private func playFinishedSound(){
if let pathResource = NSBundle.mainBundle().pathForResource("3000", ofType: "mp3"){
let finishedStepSound = NSURL(fileURLWithPath: pathResource)
audioPlayer = AVAudioPlayer()
do {
audioPlayer = try AVAudioPlayer(contentsOfURL: finishedStepSound)
if(audioPlayer!.prepareToPlay()){
print("preparation success")
audioPlayer!.delegate = self
if(audioPlayer!.play()){
print("Sound play success")
}else{
print("Sound file could not be played")
}
}else{
print("preparation failure")
}
}catch{
print("Sound file could not be found")
}
}else{
print("path not found")
}
}
AVAudioPlayer Swift 3 not playing sound
You need to move the AVPlayer
's declaration to class-level. AVPlayer
can't play sounds when you declare them in methods.
class ViewController: UIViewController {
var player: AVAudioPlayer? // <-- notice here
@IBAction func hornButtonPressed(_ sender: Any) {
playSound()
hornLabel.text = "Toet!!!"
}
@IBOutlet weak var hornLabel: UILabel!
func playSound(){
let sound = Bundle.main.url(forResource: "Horn", withExtension: "mp3")
do {
player = try AVAudioPlayer(contentsOf: sound!)
guard let player = player else { return }
player.prepareToPlay()
player.play()
} catch let error {
print(error.localizedDescription)
}
}
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
iOS app does not play audio while background
You need to set your app Capabilities Background Modes (Audio and AirPlay) and set your AVAudioSession category to AVAudioSessionCategoryPlayback and set it active.
Please Refer to this link below :
How to play audio in background with Swift?
Related Topics
Initialization of 'Unsafepointer<Int>' Results in a Dangling Pointer
Wrong Text Height When Text Contains Emoji
Swift - Add Same Navigation Bar Items to Every Page
How to Show Viewcontroller from a Non-Viewcontroller Helper Class
CSS Flexible Box Layout on Ipad
How to Know Which Line of Code Has Caused My iOS App to Crash in Xcode 9
Go Back to View Controller from Skscene
Passing Values from One View Controller to Another in Swift
Uitableview Automatic Dimension Not Working Correctly
My App Is Getting Crashed on UIdocumentpickerviewcontroller
Trim End Off of String in Swift, Getting Error at Runtime
Convert Rgb Image to 1 Channel Image (Black/White)
Why Is Optional("Text") - Swift
Alamofire Request Gets Stuck When Entering Background