AVAudioPlayer目标声音不播放 - 斯威夫特(AVAudioPlayer Object S

2019-10-21 02:52发布

我曾经为了起到隔音下面创建一个对象类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()
        }
    }
}

Answer 1:

因为你的MusicAudio类被释放你没有得到任何声音。 你需要做的变种,声音,一个属性,而不是一个局部变量。

class ViewController: UIViewController {

    var sound = MusicAudio()

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

}


文章来源: AVAudioPlayer Object Sound Not Playing - Swift