Swift / Xcode:如何在每月的每一天播放不同的声音?

时间:2018-09-08 23:39:18

标签: swift xcode

您好,谢谢您的任何想法!

我的简单应用程序有一个按钮,当按下该按钮时会发出声音。我希望按钮在每月的每一天播放不同的声音。这可能吗?如果是这样,什么代码可以实现?

这是我到目前为止的代码:

var musicEffect: AVAudioPlayer = AVAudioPlayer ()

override func viewDidLoad() {

    super.viewDidLoad()

    let musicFile = Bundle.main.path(forResource: "0001", ofType: ".mp3")

    do {
        try musicEffect = AVAudioPlayer (contentsOf: URL (fileURLWithPath: musicFile!))
    }

    catch {
        print(error)
    }
}

override func didReceiveMemoryWarning() {

    super.didReceiveMemoryWarning()
}


@IBAction func playMusic(_ sender: Any) {

    musicEffect.play()
}

再次感谢!

2 个答案:

答案 0 :(得分:1)

日历功能component(_:from:)将为您提供每月的某天。从那里很容易:

let calendar = Calendar.current

let date = Date()
let dayOfMonth = calendar.component(.day, from: date)  //Get the day of the month as an Int
let filename = String(format: "%04d", dayOfMonth)  //Convert to a string "00xx"
let musicFile = Bundle.main.path(forResource: filename, ofType: ".mp3") //Try to find a sound file

答案 1 :(得分:0)

通过使用Calendar的{​​{1}}方法,您可以从component(from:)对象中提取月份(或其他日期成分),这将使您可以执行自己想做的事情。