问题
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