iOS版雨燕:声音不玩iPhone模拟器 [英] iOS Swift: Sound not playing on iPhone Simulator

查看:202
本文介绍了iOS版雨燕:声音不玩iPhone模拟器的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在我的iOS应用斯威夫特,我想上的一个按钮的点击播放声音。

In my iOS Swift application, and i am trying to play sound on click of a button.

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

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

I am running the application in iOS iPhone Simulator. I have doorbell.mp3 added to the application. In debug mode i can see that soundURL has a value and it is not nil.

有没有错误,但声音不玩了。

There are no errors, but the sound does not play.

推荐答案

您只需将您的audioPlayer申报你的方法。尝试是这样的:

You just need to move the declaration of your audioPlayer out of your method. Try like this:

var audioPlayer:AVAudioPlayer!

func playSound() {
    if let soundURL = NSBundle.mainBundle().URLForResource("doorbell", withExtension: "mp3") {
         audioPlayer = AVAudioPlayer(contentsOfURL: soundURL, error: nil)
         audioPlayer.prepareToPlay()
         audioPlayer.play()
    }
}

这篇关于iOS版雨燕:声音不玩iPhone模拟器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆