iPhone无法播放声音,但模拟器可以播放声音

时间:2018-09-05 07:43:20

标签: ios swift avfoundation

我正在开发Flashlight应用。 在这个应用程序中,我想使用AVFoundation播放声音。 当我运行该应用程序时,声音文件在Xcode模拟器上播放良好。但是,在我的iPhone设备上,声音文件没有播放。 请看一下我的代码。

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)

    }

}

1 个答案:

答案 0 :(得分:0)

在prepareSound方法中添加两行代码,它将起作用。

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 :(
    }
}