首页 文章

Swift AVAudioPlayer 不播放声音

提问于
浏览
2

我想在我的 Swift 应用程序中播放两个声音文件。 “C1_bip.aif”和“false.aif”。它们都在项目的同一个文件夹中。

但是,当我启动应用程序时,播放 C1_bip 声音,而不是错误的声音,它会向控制台输出错误。

声音文件是相同的文件类型,我可以在 Xcode 的项目浏览器中播放它们。

if let path = NSBundle.mainBundle().pathForResource("C1_bip", ofType: "aif") {
        audioPlayer = AVAudioPlayer(contentsOfURL: NSURL(fileURLWithPath: path), 
        fileTypeHint: "aif", error: nil)

        if let sound = audioPlayer {

            sound.prepareToPlay()
            sound.play()
        }
    }
    else {
        println("Error")
    }

   if let path = NSBundle.mainBundle().pathForResource("false", ofType: "aif") {
        audioPlayer = AVAudioPlayer(contentsOfURL: NSURL(fileURLWithPath: path), 
        fileTypeHint: "aif", error: nil)

        if let sound = audioPlayer {

            sound.prepareToPlay()
            sound.play()
        }
    }
    else {
        println("Error")
    }

1 回答

  • 1

    这是我在测试项目中所做的:

    let musicPath = NSBundle.mainBundle().pathForResource("bgmusic", ofType: "mp3")
        let url = NSURL(fileURLWithPath: musicPath!)
    
        do{
            audioPlayer = try AVAudioPlayer(contentsOfURL: url)
        }catch _ {
            audioPlayer = nil
        }
        audioPlayer.numberOfLoops = -1
        audioPlayer.prepareToPlay()
        audioPlayer.play()
    

    它确实有效 well:)

相关问题