我正在尝试将按钮标签传递给我的多媒体文件名。 不幸的是,它不起作用。
想法是当我按下名为“cat”的按钮时,它将播放名为“cat”、“mp3”的文件 如果我按下标签为“cow”的按钮,它将播放文件名为“cow”的声音。
所以我已经尝试了不同的变体,但我无法让它工作。如果你们有一些想法,请帮助。
import UIKit
import AVFoundation
class ViewController: UIViewController {
var audioPlayer: AVAudioPlayer!
override func viewDidLoad() {
super.viewDidLoad()
}
func playAudio() {
do {
self.audioPlayer = try AVAudioPlayer(contentsOfURL: NSURL(fileURLWithPath: NSBundle.mainBundle().pathForResource("buttonName", ofType: "mp3")!))
self.audioPlayer.play()
} catch {
print("Error")
}
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
@IBAction func playSound(sender: AnyObject) {
let buttonName = sender.currentTitle!
playAudio()
}
}
最佳答案
我不是 Swift 专家,但我不认为 LLVM 可以为你解决这些问题:
您将
buttonName
初始化为局部变量,并且没有将其传递给playAudio()
(无论如何都不接受参数),它是 100%对我不起作用。由于您没有将本地
buttonName
作为参数传递给playAudio()
,因此您无法在函数作用域内获取按钮名称。另外,您使用"buttonName"
,它是一个String
对象,甚至不是变量。您的包中没有名为buttonName.mp3
的文件,因此不会发生任何事情(总是print("Error")
)。
类似这样的东西应该可以工作:(未经测试,但应该是类似的)
import UIKit
import AVFoundation
class ViewController: UIViewController {
var audioPlayer: AVAudioPlayer!
override func viewDidLoad() {
super.viewDidLoad()
}
func playAudio(buttonName: String!) {
do {
self.audioPlayer = try AVAudioPlayer(contentsOfURL: NSURL(fileURLWithPath: NSBundle.mainBundle().pathForResource(buttonName, ofType: "mp3")!))
self.audioPlayer.play()
} catch {
print("Error")
}
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
@IBAction func playSound(sender: AnyObject) {
let buttonName = sender.currentTitle!
playAudio(buttonName)
}
}
关于ios - 如何将按钮标题传递给多媒体文件名 Swift?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35875854/