Search code examples
swiftavfoundationavaudioplayersimulator

sound is playing in simulator but not on physical device


My xcode sound is not playing on a ipad but is playing on the xcode simulator. I downloaded my app from the appstore and the sound was not there as well. I have tried multiple file formats including mp3, aac,wav etc and none of them are playing. I dont know what is going on because I have used this code before and it worked fine.

import UIKit;import AVFoundation

class ViewController: UIViewController {

    var player : AVAudioPlayer?
    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view.
        let path = Bundle.main.path(forResource: "bell.mp3", ofType:nil)!
        let url = URL(fileURLWithPath: path)

        do {
            print("ran")
            player = try AVAudioPlayer(contentsOf: url)
            player?.play()
        } catch {
            // couldn't load file :(
        }
    }


}

Solution

  • 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)
    }