Kazaka Nelson
Kazaka Nelson

Reputation: 168

iPhone doesn't play sound but simulator can play sound

I am developing Flashlight app. In this app, I wanna play sound using AVFoundation. When I ran the app, the sound file played well on Xcode simulator. However, on my iPhone device, the sound file didn't play. Please take a look at my codes.

import UIKit
import AVFoundation
import os.log

class ViewController: UIViewController {

    @IBOutlet weak var switchButton: UIButton!
    @IBOutlet weak var flashImageView: UIImageView!

    var isOn = false
    var soundPlayer: AVAudioPlayer?

    override func viewDidLoad() {
        super.viewDidLoad()
        prepareSound()

    }

    func prepareSound() {
        let path = Bundle.main.path(forResource: "switch", ofType:"wav")!
        let url = URL(fileURLWithPath: path)

        do {
            soundPlayer = try AVAudioPlayer(contentsOf: url)
            soundPlayer?.prepareToPlay()
        } catch {
            // couldn't load file :(
        }
    }

    func toggleTorch(on: Bool) {
        guard let device = AVCaptureDevice.default(for: .video) else { return }

        if device.hasTorch {
            do {
                try device.lockForConfiguration()

                if on == true {
                    device.torchMode = .on
                } else {
                    device.torchMode = .off
                }

                device.unlockForConfiguration()
            } catch {
                print("Torch could not be used")
            }
        } else {
            print("Torch is not available")
        }
    }

    @IBAction func switchTapped(_ sender: Any) {
        isOn = !isOn
        soundPlayer?.play()
        os_log("sound played")
        toggleTorch(on: isOn)

        flashImageView.image = isOn ? #imageLiteral(resourceName: "onBG") : #imageLiteral(resourceName: "offBG")
        switchButton.setImage( isOn ? #imageLiteral(resourceName: "onSwitch") : #imageLiteral(resourceName: "offSwitch"), for: .normal)

    }

}

Upvotes: 0

Views: 70

Answers (1)

Mohan Ramanathan
Mohan Ramanathan

Reputation: 2209

Add the two lines of code in prepareSound method, It will work.

func prepareSound() {
    let session = AVAudioSession.sharedInstance()
    try? session.setCategory(AVAudioSessionCategoryPlayback)

    let path = Bundle.main.path(forResource: "switch", ofType:"wav")!
    let url = URL(fileURLWithPath: path)

    do {
        soundPlayer = try AVAudioPlayer(contentsOf: url)
        soundPlayer?.prepareToPlay()
    } catch {
        // couldn't load file :(
    }
}    

Upvotes: 0

Related Questions