播放与plist中的项目关联的音频文件

时间:2016-05-05 09:00:24

标签: swift audio

我的应用程序中有几个地方有音频,而且大部分都是直接的,并且可以正常工作,例如

func ayuh() {
        do {
            audioPlayer =  try AVAudioPlayer(contentsOfURL: NSURL(fileURLWithPath: NSBundle.mainBundle().pathForResource("ayuhSound2", ofType: "mp3")!))
            audioPlayer!.play()

        } catch {
            print("Error")
        }
    }

现在我正在尝试在我的plist play中附加特定问题的音频文件。我试过这个:

 func nextQuestion() {
    let currentQuestion = mcArray![questionIdx]

    answers = currentQuestion["Answers"] as! [String]
    correctAnswer = currentQuestion["CorrectAnswer"] as? String
    question = currentQuestion["Question"] as? String

    cardButton.enabled = false
    titlesForButtons()
    self.bonusCoin.hidden = true
    //this code above works to bring up the question and various answers

    audio = currentQuestion["Audio"] as? String
    do {
        mcaudioPlayer =  try AVAudioPlayer(contentsOfURL: NSURL(fileURLWithPath: NSBundle.mainBundle().pathForResource(audio, ofType: "mp3")!))

        mcaudioPlayer!.play()

    } catch {
        print("Error")
    }

            mcaudioPlayer!.play()

        } catch {
            print("Error")
        }

但是这只会在列表中反复播放每个问题的第一个音频文件。 here are the audio files so far

I want the before_lepage.mp3 to play when this question appears from the array in my trivia app

我是如何得到它来播放plist中关联的音频文件的?

1 个答案:

答案 0 :(得分:0)

我得到了它(在朋友的帮助下);)

func nextQuestion() {

        let currentQuestion = mcArray![questionIdx]

        answers = currentQuestion["Answers"] as! [String]

        correctAnswer = currentQuestion["CorrectAnswer"] as? String

        question = currentQuestion["Question"] as? String

        cardButton.enabled = false

        titlesForButtons()

        self.bonusCoin.hidden = true

        audio = currentQuestion["Audio"] as? String

        createPlayerItem(audio!, ofType: "mp3")

        queuePlayer.play()

        //queuePlayer.removeAllItems()

    }



    func createPlayerItem(item: String, ofType type: String) {

        let path = NSBundle.mainBundle().pathForResource(item, ofType: type)

        let url = NSURL.fileURLWithPath(path!)

        let item = AVPlayerItem(URL: url)

        queuePlayer.insertItem(item, afterItem: nil)   

    }