Ios 声音文件在模拟器中运行良好,但在iPhone中不起作用

Ios 声音文件在模拟器中运行良好,但在iPhone中不起作用,ios,iphone,swift,Ios,Iphone,Swift,我有一个应用程序,只要点击一个按钮就可以播放声音。但是,在真正的设备上没有声音。我检查了stackoverflow中其他人提供的所有解决方案。似乎什么都不管用。应用程序没有崩溃。它就是不能播放声音。在模拟器中,它工作得很好。区分大小写没有问题。此外,手机不是静音的 代码: 按下按钮时: let soundPath = Bundle.main.path(forResource: "bell-ringing-01", ofType: "mp3") audioPlayer = try! AVAudio

我有一个应用程序,只要点击一个按钮就可以播放声音。但是,在真正的设备上没有声音。我检查了stackoverflow中其他人提供的所有解决方案。似乎什么都不管用。应用程序没有崩溃。它就是不能播放声音。在模拟器中,它工作得很好。区分大小写没有问题。此外,手机不是静音的

代码:

按下按钮时:

let soundPath = Bundle.main.path(forResource: "bell-ringing-01", ofType: "mp3")
audioPlayer = try! AVAudioPlayer(contentsOf: URL(fileURLWithPath: soundPath!))
audioPlayer?.play()

编译和运行时也没有错误。应用程序加载良好。

已解决!下面的代码可以工作。按下播放按钮后,将播放铃声

func playSound(){

让soundURL=Bundle.main.url(用于资源:“bell-ringing-01”,带扩展名:“mp3”)

}

仅在模拟器中有效,但在iPhone 7中无效的代码:

func playSound(){

没有添加AVAudioSession,代码只能在模拟器中运行,但不能在我的iPhone 7中运行


我猜添加这两行代码解决了现有代码中的问题:

尝试AVAudioSession.sharedInstance().setCategory(AVAudioSessionCategoryPlayback)

尝试AVAudioSession.sharedInstance().setActive(true)


文件名大小写在实际设备上很重要。文件名是否真的命名为
bell-ringing-01.mp3
,而不是类似的名称,如
bell-ringing-01.mp3
bell-ringing-01.mp3
或任何其他变体?文件名为“bell-ringing-01.mp3”.我重新检查了它只是为了确定。这总是两件事之一:如@rmaddy所说的区分大小写或静音开关打开(或音量降低).事实上,我反复检查了一遍。区分大小写和静音开关没有问题。我不知道为什么代码在模拟器中运行良好,但在iPhone 7上运行不好。这与Swift 4和新版iOS有关吗?
let soundPath = Bundle.main.path(forResource: "bell-ringing-01", ofType: "mp3")
audioPlayer = try! AVAudioPlayer(contentsOf: URL(fileURLWithPath: soundPath!))
audioPlayer?.play()
    do{
        try AVAudioSession.sharedInstance().setCategory(AVAudioSessionCategoryPlayback)
        try AVAudioSession.sharedInstance().setActive(true)
        try audioPlayer = try AVAudioPlayer(contentsOf: soundURL!)

    }

    catch{

        print(error)
    }
   audioPlayer.play()
   // let soundURL = Bundle.main.url(forResource: selectedSoundFileName, withExtension: "wav")

    let soundPath = Bundle.main.path(forResource: "bell-ringing-01", ofType: "mp3")

    audioPlayer = try! AVAudioPlayer(contentsOf: URL(fileURLWithPath: soundPath!))
    audioPlayer?.play()




}