ios - 如何将按钮标题传递给多媒体文件名 Swift?

标签 ios swift

我正在尝试将按钮标签传递给我的多媒体文件名。 不幸的是,它不起作用。

想法是当我按下名为“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/

相关文章:

ios - UIScrollView 在 iOS7 中不滚动自动布局

ios - HidesBottomBarWhenPushed 离开指示器

ios - 将 "user-taken"照片保存在详细 View 中,并在 TableView 中单击时加载它

iphone - iOS5 上的 CCKeyDerivationPBKDF

ios - 如何在 NSPredicate 中定义临时变量?

iOS NSMutableURLRequest 授权 header

swift - queryOrdered 并不总是以正确的顺序返回 tableViewCell 上的数据

ios - 如何获取函数抛出的错误列表?

ios - 单击指定单元格后获取搜索栏占位符中的 TableView 单元格文本值

ios - 在 iOS 上使用 TestFlight 进行应用内更新