AVAudioPlayer对象声音没有播放 - Swift

时间:2014-10-10 15:34:11

标签: ios audio avfoundation avaudioplayer nsobject

我在下面创建了一个AVAudioPlayer的对象类,以便发出噪音:

class MusicAudio: NSObject, AVAudioPlayerDelegate {

    var bassAudio   : AVAudioPlayer! = AVAudioPlayer()

    override init() {
        super.init()
        let bassAudioPath       = NSBundle.mainBundle().pathForResource("Raw", ofType:"mp3")

        let fileURL = NSURL(fileURLWithPath: bassAudioPath!)
        bassAudio = AVAudioPlayer(contentsOfURL: fileURL, error: nil)
        bassAudio.currentTime = 0
        bassAudio.volume = 1.0
        bassAudio.delegate = self
    }

    func adjustAudioLayerState(volumeOn:Bool, layer:AudioLayerState) {

        if layer == AudioLayerState.Bass {
            self.bassAudio.prepareToPlay()
            self.bassAudio.play()
        }
    }
}

为了播放噪音,我通过以下方式致电课程:

@IBAction func testSound() {
    var sound:MusicAudio = MusicAudio()
    sound.adjustAudioLayerState(true, layer: AudioLayerState.Bass)

}

但是我没有播放任何音频,有人能发现我的实施问题吗?

编辑:在rdelmar回答之后

var bassAudio   : AVAudioPlayer! = AVAudioPlayer()

class MusicAudio: NSObject, AVAudioPlayerDelegate {

    override init() {
        super.init()
        let bassAudioPath       = NSBundle.mainBundle().pathForResource("Raw", ofType:"mp3")

        let fileURL = NSURL(fileURLWithPath: bassAudioPath!)
        bassAudio = AVAudioPlayer(contentsOfURL: fileURL, error: nil)
        bassAudio.currentTime = 0
        bassAudio.volume = 1.0
        bassAudio.delegate = self
    }

    func adjustAudioLayerState(volumeOn:Bool, layer:AudioLayerState) {

        if layer == AudioLayerState.Bass {
            self.bassAudio.prepareToPlay()
            self.bassAudio.play()
        }
    }
}

1 个答案:

答案 0 :(得分:4)

由于您的MusicAudio类正在取消分配,因此您无法获得任何声音。你需要制作var,sound,属性,而不是局部变量。

class ViewController: UIViewController {

    var sound = MusicAudio()

    @IBAction func testSound() {
        self.sound.adjustAudioLayerState(true, layer: AudioLayerState.Bass)
    }

}