【问题标题】:Sound file works fine in simulator but does not work in iPhone声音文件在模拟器中工作正常,但在 iPhone 中不起作用
【发布时间】:2018-08-20 00:32:53
【问题描述】:

如果单击按钮,我有一个应用程序会播放声音。但是,在真实设备上没有声音。我在stackoverflow中检查了其他人已经提供的所有解决方案。似乎没有任何效果。该应用程序不会崩溃。它只是不播放声音。在模拟器中它完美地工作。区分大小写没有问题。另外,手机没有静音。

代码:

var audioPlayer : AVAudioPlayer!

按下按钮时:

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

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

【问题讨论】:

  • 文件名大小写在真实设备上很重要。文件真的是否命名为bell-ringing-01.mp3,而不是类似bell-ringing-01.MP3Bell-ringing-01.mp3 或任何其他变体?
  • 文件名为“bell-ringing-01.mp3”。为了确定,我重新检查了一遍。
  • 这始终是两件事之一:@rmaddy 所说的区分大小写或静音开关打开(或降低音量)。
  • 其实我检查了一遍又一遍。区分大小写和静音开关没有问题。我不知道为什么代码在模拟器中运行良好,但在 iPhone 7 上却没有。这与 Swift 4 和新版本的 iOS 有关吗?

标签: ios iphone swift


【解决方案1】:

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

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

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

【讨论】:

    【解决方案2】:

    解决了!以下代码有效。按下播放按钮后会播放铃声

    func playSound(){

    让 soundURL = Bundle.main.url(forResource: "bell-ringing-01", withExtension: "mp3")

        do{
            try AVAudioSession.sharedInstance().setCategory(AVAudioSessionCategoryPlayback)
            try AVAudioSession.sharedInstance().setActive(true)
            try audioPlayer = try AVAudioPlayer(contentsOf: soundURL!)
    
        }
    
        catch{
    
            print(error)
        }
       audioPlayer.play()
    

    }

    仅适用于模拟器的代码,不适用于 iPhone 7:

    func playSound() {

       // 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()
    
    
    
    
    }
    

    在不添加 AVAudioSession 的情况下,代码仅在模拟器中运行,而不在我的 iPhone 7 中运行。

    【讨论】:

      猜你喜欢
      • 2010-09-23
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-06-18
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多