gpt4 book ai didi

Swift,如何在按下按钮时播放声音

转载 作者:行者123 更新时间:2023-11-30 13:24:30 29 4
gpt4 key购买 nike

我是编程新手,开始学习 Swift 来制作一个有趣的钢琴应用程序。

按下按钮时无法播放声音。我搜索了一些网站,但我太初学者无法理解......

http://www.tmroyal.com/playing-sounds-in-swift-avaudioplayer.html http://www.rockhoppertech.com/blog/swift-avfoundation/

您能告诉我如何在按下“PainoC”按钮时播放“C.m4a”声音吗?

这是我的“viewcontroller.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 :(
}
}

关于Swift,如何在按下按钮时播放声音,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37380719/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com