用AVAudioPlayer播放声音

我试图用AVAudioPlayer播放声音,但它不会工作。

编辑1:仍然不起作用。

编辑2 :此代码的作品。 我的设备处于静音模式。

 import UIKit import AVFoundation class ViewController: UIViewController { var audioPlayer = AVAudioPlayer() override func viewDidLoad() { super.viewDidLoad() var alertSound = NSURL(fileURLWithPath: NSBundle.mainBundle().pathForResource("button-09", ofType: "wav")) println(alertSound) var error:NSError? audioPlayer = AVAudioPlayer(contentsOfURL: alertSound, error: &error) audioPlayer.prepareToPlay() audioPlayer.play() } 

对您的代码进行了修改:

 import UIKit import AVFoundation class ViewController: UIViewController { var audioPlayer = AVAudioPlayer() override func viewDidLoad() { super.viewDidLoad() var alertSound = NSURL(fileURLWithPath: NSBundle.mainBundle().pathForResource("button-09", ofType: "wav")) println(alertSound) // Removed deprecated use of AVAudioSessionDelegate protocol AVAudioSession.sharedInstance().setCategory(AVAudioSessionCategoryPlayback, error: nil) AVAudioSession.sharedInstance().setActive(true, error: nil) var error:NSError? audioPlayer = AVAudioPlayer(contentsOfURL: alertSound, error: &error) audioPlayer.prepareToPlay() audioPlayer.play() } } 

Swift 3:

 import UIKit import AVFoundation class ViewController: UIViewController { private var audioPlayer: AVAudioPlayer? override func viewDidLoad() { super.viewDidLoad() let alertSound = URL(fileURLWithPath: Bundle.main.path(forResource: "button-09", ofType: "wav")!) print(alertSound) try! AVAudioSession.sharedInstance().setCategory(AVAudioSessionCategoryPlayback) try! AVAudioSession.sharedInstance().setActive(true) try! audioPlayer = AVAudioPlayer(contentsOf: alertSound) audioPlayer!.prepareToPlay() audioPlayer!.play() } } 

根据Swift 2的代码应该是

 func playSound(soundName: String) { let coinSound = NSURL(fileURLWithPath: NSBundle.mainBundle().pathForResource(soundName, ofType: "m4a")!) do{ let audioPlayer = try AVAudioPlayer(contentsOfURL:coinSound) audioPlayer.prepareToPlay() audioPlayer.play() }catch { print("Error getting the audio file") } } 

您的audio播放将在viewDidLoad完成后立即释放,因为您将其分配给本地variables。 你需要创build一个属性来保持它。

该解决scheme是针对AudioPlayer的udemy iOS练习中的一个,其在导航栏中具有播放/暂停/停止button作为条形button项目

在Swift 2.1中,你可以使用下面的代码

 import UIKit import AVFoundation class ViewController: UIViewController { var player:AVAudioPlayer = AVAudioPlayer() override func viewDidLoad() { super.viewDidLoad() let audioPath = NSBundle.mainBundle().pathForResource("ARRehman", ofType: "mp3") var error:NSError? = nil do { player = try AVAudioPlayer(contentsOfURL: NSURL(fileURLWithPath: audioPath!)) } catch { print("Something bad happened. Try catching specific errors to narrow things down") } } @IBAction func play(sender: UIBarButtonItem) { player.play() } @IBAction func stop(sender: UIBarButtonItem) { player.stop() print(player.currentTime) player.currentTime = 0 } @IBAction func pause(sender: UIBarButtonItem) { player.pause() } @IBOutlet weak var sliderval: UISlider! @IBAction func slidermov(sender: UISlider) { player.volume = sliderval.value print(player.volume) } } 

这将工作…..

 import UIKit import AVFoundation class ViewController: UIViewController { var ding:AVAudioPlayer = AVAudioPlayer() override func viewDidLoad() { super.viewDidLoad() prepareAudios() ding.play() } func prepareAudios() { var path = NSBundle.mainBundle().pathForResource("ding", ofType: "mp3") ding = AVAudioPlayer(contentsOfURL: NSURL(fileURLWithPath: path!), error: nil) ding.prepareToPlay() } } 

这是一个相当古老的问题,但我没有看到与Swift 3.0一起工作的答案,所以我现代化了代码并添加了一些安全检查来防止崩溃。

我也采取了把玩部分拉到自己的function,以帮助重新使用任何人遇到这个答案的方法。

 import UIKit import AVFoundation class ViewController: UIViewController { var audioPlayer: AVAudioPlayer? override func viewDidLoad() { super.viewDidLoad() play(for: "button-09", type: "wav") } func play(for resource: String, type: String) { // Prevent a crash in the event that the resource or type is invalid guard let path = Bundle.main.path(forResource: resource, ofType: type) else { return } // Convert path to URL for audio player let sound = URL(fileURLWithPath: path) do { audioPlayer = try AVAudioPlayer(contentsOf: sound) audioPlayer?.prepareToPlay() audioPlayer?.play() } catch { // Create an assertion crash in the event that the app fails to play the sound assert(false, error.localizedDescription) } } } 

使用此function在Swift中发声(您可以在想要发声的位置使用此function。)

首先添加SpriteKit和AVFoundation框架。

 import SpriteKit import AVFoundation func playEffectSound(filename: String){ runAction(SKAction.playSoundFileNamed("\(filename)", waitForCompletion: false)) }// use this function to play sound playEffectSound("Sound File Name With Extension") // Example :- playEffectSound("BS_SpiderWeb_CollectEgg_SFX.mp3")