我是编程的初学者,并开始学习Swift,以制作一款有趣的钢琴应用。
按下按钮时我无法播放声音。我已经搜索了一些网站,但是我还是个初学者,无法理解…
http://www.tmroyal.com/playing-sounds-in-swift-avaudioplayer.html http://www.rockhoppertech.com/blog/swift- avfoundation/
您能告诉我按“ PainoC”按钮时如何播放“ C.m4a”声音吗?
这是我的“ view controller.swift”。
import UIKit class ViewController: UIViewController { override func viewDidLoad() { super.viewDidLoad() } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() } @IBAction func PianoC(sender: AnyObject) { } }
希望对您有帮助。
import UIKit import AVFoundation class ViewController: UIViewController { // make sure to add this sound to your project var pianoSound = NSURL(fileURLWithPath: NSBundle.mainBundle().pathForResource("C", ofType: "m4a")) var audioPlayer = AVAudioPlayer() override func viewDidLoad() { super.viewDidLoad() audioPlayer = AVAudioPlayer(contentsOfURL: pianoSound, error: nil) audioPlayer.prepareToPlay() } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() } @IBAction func PianoC(sender: AnyObject) { audioPlayer.play() } }
最新的Swift 4.2:
let pianoSound = URL(fileURLWithPath: Bundle.main.path(forResource: "btn_click_sound", ofType: "mp3")!) var audioPlayer = AVAudioPlayer() @IBAction func PianoC(sender: AnyObject) { do { audioPlayer = try AVAudioPlayer(contentsOf: pianoSound) audioPlayer.play() } catch { // couldn't load file :( } }