简体   繁体   中英

AVAudioPlayer Object Sound Not Playing - Swift

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

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

}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM