快速播放声音在模拟器中有效,但不适用于 iPhone



我编写了以下代码,当按下按钮时会播放声音,它在模拟器(IPhone7(上完美运行,但在iPhone X上运行时则不然。 我的手机上的静音按钮未打开。

import UIKit
import AVFoundation
class ViewController: UIViewController, AVAudioPlayerDelegate{
var soundPlayer : AVAudioPlayer!
override func viewDidLoad() {
super.viewDidLoad()
}
@IBAction func notePressed(_ sender: UIButton) {
playNote(noteIndex: sender.tag)
}
func playNote(noteIndex : Int){
let soundURL = Bundle.main.url(forResource: "note(noteIndex)", withExtension: "wav")
do {
try AVAudioSession.sharedInstance().setCategory(.playback, mode: .default, options:[])
try AVAudioSession.sharedInstance().setActive(true)
soundPlayer = try AVAudioPlayer(contentsOf:soundURL!)
} catch {
print (error)
}
soundPlayer.play()
}
}

我终于找到了解决方案:

转到:文件>项目设置...,将"派生数据:"更改为"项目相对位置",单击"完成"。

这对我有用。

最新更新