简体   繁体   中英

AVAudioPlayer doesn't play sound?

I have a AVAudioPlayer in a seperate class, which I load into a ViewController. Here's the code:

import Foundation
import AVFoundation

class SoundController {

    var audioPlayer: AVAudioPlayer!

    init() {
    }

    func playAudio() {
        let path = NSBundle.mainBundle().pathForResource("ring-ring", ofType: "aiff", inDirectory: "Media" )!
        let url = NSURL(fileURLWithPath: path)

        do {
            print("Let's play the sound")
            let sound = try AVAudioPlayer(contentsOfURL: url)
            self.audioPlayer = sound
            sound.play()
        } catch {
            print("Error playing sound file")
        }
    }
}

And here is the ViewController

override func viewDidLoad() {
        super.viewDidLoad()

        let sound = SoundController()
        sound.playAudio()
    }

Everything compiles and I get the console output "Let's play the sound", but no matter which device I test on, the sound doesn't play. Any advice what's wrong?

You assign your audioPlayer the wrong way I think this should work.

import Foundation
import AVFoundation
var audioPlayer: AVAudioPlayer!

class SoundController {
    class func playAudio() {
        let path = NSBundle.mainBundle().pathForResource("ring-ring", ofType: "aiff", inDirectory: "Media" )!
        let url = NSURL(fileURLWithPath: path)

        do {
            print("Let's play the sound")
            audioPlayer = try AVAudioPlayer(contentsOfURL: url)
            audioPlayer.prepareToPlay()
        } catch {
            print("Error playing sound file")
        }
    }
}

override func viewDidLoad() {
    super.viewDidLoad()
    SoundController.playAudio()
    audioPlayer.play()
}

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