Swift 斯威夫特,如何在按下按钮时播放声音
我是一名编程新手,我开始学习Swift来制作一个有趣的钢琴应用程序 我按下按钮时无法播放声音。 我已经搜索了一些网站,但我太初学者,无法理解 请您告诉我,当按下“PainoC”按钮时,如何播放“C.m4a”声音 这是我的“视图控制器.swift”Swift 斯威夫特,如何在按下按钮时播放声音,swift,Swift,我是一名编程新手,我开始学习Swift来制作一个有趣的钢琴应用程序 我按下按钮时无法播放声音。 我已经搜索了一些网站,但我太初学者,无法理解 请您告诉我,当按下“PainoC”按钮时,如何播放“C.m4a”声音 这是我的“视图控制器.swift” 我希望它能帮助你 import UIKit import AVFoundation class ViewController: UIViewController { // make sure to add this sound to you
我希望它能帮助你
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 :(
}
}
import UIKit
import AVFoundation
class QuestionView: UIViewController {
var btnButton = UIButton()
var player = AVAudioPlayer()
override func viewDidLoad() {
super.viewDidLoad()
btnButton.frame = CGRect(x: 100, y: 100, width: 100, height: 100)
btnButton.backgroundColor = UIColor.blue
btnButton.addTarget(self, action: #selector(ButtonSound), for: .touchUpInside)
}
func ButtonSound() {
do {
// make sure to add this sound to your project
let audioPath = Bundle.main.path(forResource: "Click", ofType: "mp3")
try player = AVAudioPlayer(contentsOf: URL(fileURLWithPath: audioPath!) as URL)
} catch {
print("Error !")
}
player.play()
}
}
import AVFoundation
class ViewController: UIViewController, ARSCNViewDelegate, ARSessionDelegate {
let popSound = Bundle.main.url(forResource: "Pop", withExtension: "mp3")
var audioPlayer = AVAudioPlayer()
override func viewDidLoad() {
do {
audioPlayer = try AVAudioPlayer(contentsOf: popSound!)
audioPlayer.play()
} catch {
print("couldn't load sound file")
}
}
Swift 3 现在的语法如下所示: 首先在代码顶部添加
import AVFoundation
,以访问AVFoundation Framework
import UIKit
import AVFoundation
class ViewController: UIViewController {
//this is your audio playback instance
var audioPlayer = AVAudioPlayer()
override func viewDidLoad() {
super.viewDidLoad()
// address of the music file.
let music = Bundle.main.path(forResource: "Music", ofType: "mp3")
// copy this syntax, it tells the compiler what to do when action is received
do {
audioPlayer = try AVAudioPlayer(contentsOf: URL(fileURLWithPath: music! ))
try AVAudioSession.sharedInstance().setCategory(AVAudioSessionCategoryAmbient)
try AVAudioSession.sharedInstance().setActive(true)
}
catch{
print(error)
}
}
//this runs the do try statement
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
@IBAction func play(_ sender: AnyObject) {
audioPlayer.play()
}
@IBAction func stop(_ sender: AnyObject) {
audioPlayer.stop()
}
}
在Swift 3中:
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 :(
}
}
import UIKit
import AVFoundation
class QuestionView: UIViewController {
var btnButton = UIButton()
var player = AVAudioPlayer()
override func viewDidLoad() {
super.viewDidLoad()
btnButton.frame = CGRect(x: 100, y: 100, width: 100, height: 100)
btnButton.backgroundColor = UIColor.blue
btnButton.addTarget(self, action: #selector(ButtonSound), for: .touchUpInside)
}
func ButtonSound() {
do {
// make sure to add this sound to your project
let audioPath = Bundle.main.path(forResource: "Click", ofType: "mp3")
try player = AVAudioPlayer(contentsOf: URL(fileURLWithPath: audioPath!) as URL)
} catch {
print("Error !")
}
player.play()
}
}
import AVFoundation
class ViewController: UIViewController, ARSCNViewDelegate, ARSessionDelegate {
let popSound = Bundle.main.url(forResource: "Pop", withExtension: "mp3")
var audioPlayer = AVAudioPlayer()
override func viewDidLoad() {
do {
audioPlayer = try AVAudioPlayer(contentsOf: popSound!)
audioPlayer.play()
} catch {
print("couldn't load sound file")
}
}
在Swift 4中:
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 :(
}
}
import UIKit
import AVFoundation
class QuestionView: UIViewController {
var btnButton = UIButton()
var player = AVAudioPlayer()
override func viewDidLoad() {
super.viewDidLoad()
btnButton.frame = CGRect(x: 100, y: 100, width: 100, height: 100)
btnButton.backgroundColor = UIColor.blue
btnButton.addTarget(self, action: #selector(ButtonSound), for: .touchUpInside)
}
func ButtonSound() {
do {
// make sure to add this sound to your project
let audioPath = Bundle.main.path(forResource: "Click", ofType: "mp3")
try player = AVAudioPlayer(contentsOf: URL(fileURLWithPath: audioPath!) as URL)
} catch {
print("Error !")
}
player.play()
}
}
import AVFoundation
class ViewController: UIViewController, ARSCNViewDelegate, ARSessionDelegate {
let popSound = Bundle.main.url(forResource: "Pop", withExtension: "mp3")
var audioPlayer = AVAudioPlayer()
override func viewDidLoad() {
do {
audioPlayer = try AVAudioPlayer(contentsOf: popSound!)
audioPlayer.play()
} catch {
print("couldn't load sound file")
}
}
在Swift 4中 这对我很管用,试试看
import UIKit
import AVFoundation
class ViewController: UIViewController, AVAudioPlayerDelegate{
var audioPlayer = AVAudioPlayer()
override func viewDidLoad() {
super.viewDidLoad()
}
@IBAction func notePressed(_ sender: UIButton) {
let soundURL = NSURL(fileURLWithPath: Bundle.main.path(forResource: "note1", ofType: "wav")!)
do{
audioPlayer = try AVAudioPlayer(contentsOf: soundURL as URL)
}catch {
print("there was some error. The error was \(error)")
}
audioPlayer.play()
}
}
如果您只需要点击效果,下面的代码将起作用。
bird文件必须在xcode中
self.run(SKAction.playSoundFileNamed("Bird.mp3", waitForCompletion:false))
谢谢你的回答,我真的很感激。很抱歉,我不习惯添加评论,,,它不起作用,我回答说…在学习Xcode和Swift一段时间后,现在我明白了你的答案。成功了!非常感谢你!为什么要将audioPlayer初始化为AVAudioPlayer()?@jpheldson是的,我也注意到了。请不要发布。无论如何,如果某个问题已有可用答案,请将该问题标记为“重复”,而不是“回答”。谢谢。@Eric Aya看看我的代码。。这与上面的答案不同。。我使用try-and-catch方法进行错误处理,这在新swiftI的x-code 7.1版(7B91b)中是必要的。我在这里没有提到答案。问题是,您发布的答案与您在另一页上发布的答案类似。这就是为什么我告诉你不要发布重复的内容,而是标记问题。当popSound返回nil时,它崩溃了。使用以下代码可以很容易地解决这个问题:
let popSound=Bundle.main.path(forResource:“pop.mp3”,ofType:nil)
audioPlayer=尝试AVAudioPlayer(contentsOf:URL(fileURLWithPath:popSound))
请避免强制展开值,因为这是一个危险的操作,可能会导致意外的应用程序崩溃。始终记住编写尽可能安全的代码。