AVAudioPlayer不播放声音?

时间:2016-04-05 14:53:29

标签: ios swift avaudioplayer

我在一个单独的类中有一个AVAudioPlayer,我将其加载到ViewController中。这是代码:

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

这是ViewController

override func viewDidLoad() {
        super.viewDidLoad()

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

一切都在编译,我得到了控制台输出"让我们播放声音",但无论我测试哪种设备,声音都不会播放。有什么建议有什么不对吗?

1 个答案:

答案 0 :(得分:0)

你认为你的audioPlayer错误的方式我认为这应该有效。

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