问题
I added the AVFoundation.framework to my project. In my project navigator I added the file "Horn.mp3", this is a sound of 1 second.
When a button is pressed (with a image of a horn) the sound should play, also should a label change it's text.
The label is changing it's text, but the sound isn't playing.
This is my code:
import UIKit
import AVFoundation
class ViewController: UIViewController {
@IBAction func hornButtonPressed(_ sender: Any) {
playSound()
hornLabel.text = "Toet!!!"
}
@IBOutlet weak var hornLabel: UILabel!
func playSound(){
var player: AVAudioPlayer?
let sound = Bundle.main.url(forResource: "Horn", withExtension: "mp3")
do {
player = try AVAudioPlayer(contentsOf: sound!)
guard let player = player else { return }
player.prepareToPlay()
player.play()
} catch let error {
print(error.localizedDescription)
}
}
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
回答1:
You need to move the AVPlayer
's declaration to class-level. AVPlayer
can't play sounds when you declare them in methods.
class ViewController: UIViewController {
var player: AVAudioPlayer? // <-- notice here
@IBAction func hornButtonPressed(_ sender: Any) {
playSound()
hornLabel.text = "Toet!!!"
}
@IBOutlet weak var hornLabel: UILabel!
func playSound(){
let sound = Bundle.main.url(forResource: "Horn", withExtension: "mp3")
do {
player = try AVAudioPlayer(contentsOf: sound!)
guard let player = player else { return }
player.prepareToPlay()
player.play()
} catch let error {
print(error.localizedDescription)
}
}
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
来源:https://stackoverflow.com/questions/42748014/avaudioplayer-swift-3-not-playing-sound