iOS Swift:声音没有播放

Jas*_*per 2 iphone audio ios swift

在我的iOS Swift应用程序中,我试图点击一个按钮播放声音.

func playSound()
    {
        var audioPlayer = AVAudioPlayer()
        let soundURL = NSBundle.mainBundle().URLForResource("doorbell", withExtension: "mp3")
        audioPlayer = AVAudioPlayer(contentsOfURL: soundURL, error: nil)
        audioPlayer.play()
}
Run Code Online (Sandbox Code Playgroud)

我正在iOS iPhone模拟器中运行该应用程序.我已将doorbell.mp3添加到应用程序中.在调试模式下,我可以看到soundURL有一个值,它不是零.

没有错误,但声音没有播放.

Leo*_*bus 8

您只需要从您的方法中移出audioPlayer的声明.试试这样:

Swift 3或更高版本

var audioPlayer = AVAudioPlayer()

func playSound() throws {
    let url = Bundle.main.url(forResource: "doorbell", withExtension: "mp3")!
    audioPlayer = try AVAudioPlayer(contentsOf: url)
    audioPlayer.prepareToPlay()
    audioPlayer.play()
}
Run Code Online (Sandbox Code Playgroud)
do { 
    try playSound() 
} catch { 
    print(error)
}
Run Code Online (Sandbox Code Playgroud)

  • 如果你在方法中声明你的玩家,它一旦完成你的方法就会不再存在. (2认同)