AVAudioPlayer Object Sound Not Playing - Swift

给你一囗甜甜゛ 提交于 2020-01-05 08:11:09

问题


I have created an object class of AVAudioPlayer below in order to play a noise:

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

To play the noise, I call the class via:

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

}

However I am not getting any audio played back, can anyone spot a problem with my implementation?

Edit: After rdelmar answer

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:


You don't get any sound because your MusicAudio class is being deallocated. You need to make the var, sound, a property, not a local variable.

class ViewController: UIViewController {

    var sound = MusicAudio()

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

}


来源:https://stackoverflow.com/questions/26302996/avaudioplayer-object-sound-not-playing-swift

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!