AVAudioPlayer在其他swift文件中调用时不会播放声音

时间:2015-06-13 17:18:59

标签: ios swift audio avaudioplayer

我有两个swift文件 - 我的ViewController:UIViewController和AudioPlayer:AVAudioPlayer。

我的AudioPlayer文件具有此功能

func seaGullSound() {

    var tmp = AVAudioPlayer()

    var seaGullSound = NSURL(fileURLWithPath: NSBundle.mainBundle().pathForResource("Gulls", ofType: "mp3")!)

    AVAudioSession.sharedInstance().setCategory(AVAudioSessionCategoryPlayback, error: nil)
    AVAudioSession.sharedInstance().setActive(true, error: nil)

    var error:NSError?

    tmp = AVAudioPlayer(contentsOfURL: seaGullSound, error: &error)
    tmp.prepareToPlay()
    tmp.play()

    println("This function got called!")
}

我正试图通过点击按钮在我的ViewController中调用该函数,使用以下代码:

@IBAction func playSound(sender: AnyObject) {
    var audio = AudioPlayer()
    audio.seaGullSound()
}

单击按钮时不播放声音。但是,print语句有效。如果我将seaGullSound()移动到ViewController文件,我可以播放音频,所以我知道mp3确实有效。我还没有将音频移动到ViewController,因为我想养成不将所有代码压缩到一个文件中的习惯。在此先感谢您的帮助。

修改

class HighScore: UIViewController {

var audioInitializer = AudioPlayer()

func updateHighScore(score:Int) -> String {
    NSUserDefaults.standardUserDefaults().integerForKey("highscore")

    //Check if score is higher than NSUserDefaults stored value and change NSUserDefaults stored value if it's true
    if score > NSUserDefaults.standardUserDefaults().integerForKey("highscore") {
        //call applause sound
        audioInitializer.applauseSound()
        //set score
        NSUserDefaults.standardUserDefaults().setInteger(score, forKey: "highscore")
        NSUserDefaults.standardUserDefaults().synchronize()
    }
    NSUserDefaults.standardUserDefaults().integerForKey("highscore")

    //use below line to reset high score for testing
    //NSUserDefaults.standardUserDefaults().removeObjectForKey("highscore")

    return String(NSUserDefaults.standardUserDefaults().integerForKey("highscore"))
}}

这是带声音的文件:

class AudioPlayer: AVAudioPlayer {

var soundMaster = AVAudioPlayer()

func tappingSound() {

    var tapSoundURL = NSBundle.mainBundle().URLForResource("tapSound", withExtension: "mp3")

    AVAudioSession.sharedInstance().setCategory(AVAudioSessionCategoryPlayback, error: nil)
    AVAudioSession.sharedInstance().setActive(true, error: nil)

    var error:NSError?

    soundMaster = AVAudioPlayer(contentsOfURL: tapSoundURL, error: &error)
    soundMaster.prepareToPlay()
    soundMaster.play()
}

//need to call in highscore.swift
func applauseSound() {
    var tapSoundURL = NSBundle.mainBundle().URLForResource("applause", withExtension: "mp3")

    AVAudioSession.sharedInstance().setCategory(AVAudioSessionCategoryPlayback, error: nil)
    AVAudioSession.sharedInstance().setActive(true, error: nil)

    var error:NSError?

    soundMaster = AVAudioPlayer(contentsOfURL: tapSoundURL, error: &error)
    soundMaster.prepareToPlay()
    soundMaster.play()
    println("did this get called?")
}}

1 个答案:

答案 0 :(得分:2)

您只需将tmp AVAudioPlayer的声明移出您的方法。将其声明为类变量。

您还应该使用URLForResource而不是pathForResource:

let seaGullSoundURL = NSBundle.mainBundle().URLForResource("Gulls", withExtension:  "mp3")!

试试这样:

import UIKit
import AVFoundation
class HighScore: UIViewController {
    var audioPlayer = AVAudioPlayer()
    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view.
    }
    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }
    func updateHighScore(score:Int) -> String {
        //Check if score is higher than NSUserDefaults stored value and change NSUserDefaults stored value if it's true
        if score > NSUserDefaults().integerForKey("highscore") {
            //call applause sound
            playAudio("applause")
            //set score
            NSUserDefaults().setInteger(score, forKey: "highscore")
        }
        //use below line to reset high score for testing
        //NSUserDefaults.standardUserDefaults().removeObjectForKey("highscore")
        return NSUserDefaults().integerForKey("highscore").description
    }
    func playAudio(audioName: String ) {
        var error:NSError?
        if let audioURL = NSBundle.mainBundle().URLForResource(audioName, withExtension: "mp3") {
            audioPlayer = AVAudioPlayer(contentsOfURL: audioURL, error: &error)
            audioPlayer.prepareToPlay()
            audioPlayer.play()
        } else if let error = error {
            println(error.description)
        }
    }
    @IBAction func playSound(sender: UIButton) {
        playAudio("Gulls")
    }
}
相关问题