Swift AVAudioPlayer无声音播放

4
我希望在我的Swift应用程序中播放两个声音文件,它们分别是"C1_bip.aif"和"false.aif"。它们都在项目的同一个文件夹中。
但是当我启动应用程序时,只会播放C1_bip声音,而false声音没有播放,并且在控制台上打印了错误信息。
这两个声音文件都是相同的文件类型,并且我可以在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")
    }

这段代码对我来说运行良好。所以请检查您添加到项目中的文件。 - Dharmesh Kheni
我不知道出了什么问题。我把文件放在项目文件夹里,但它不起作用。但是之前存在的那个却完美地工作着... - Michael Krautsieder
使用这段代码,我可以播放两个文件。所以你应该尝试再次添加false.aif文件。 - Dharmesh Kheni
请删除那个旧文件。 - Dharmesh Kheni
1个回答

2

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

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

它确实运行良好 :)

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接