【发布时间】:2016-05-25 19:41:33
【问题描述】:
我仍然是编码的初学者,但我正在开发一个非常基本的音乐播放器,以了解 Swift 的工作原理。
////Functions
//Play chosen file function
func playChosenFile() {
//Set up the music file URL.
let musicFilePathURL = MenuBarModel.mainMenu.URL
if musicFilePathURL != nil {
//Initialize audioPlayer with safety.
do {
try audioPlayer = AVAudioPlayer(contentsOfURL: musicFilePathURL!)
}
catch {
}
}
else if musicFilePathURL == nil {
//Some code that will make the player do nothing.
}
}
//Play function
func play() {
playChosenFile()
audioPlayer.play()
}
所以如果我使用 NSOpenPanel() 选择音频文件,musicFilePathURL 会使用 URL 进行初始化。
如果我确实使用 NSOpenPanel() 选择了一个文件,那么 musicFilePathURL 具有所选文件的位置,然后传递给 AVAudioPlayer。一旦我按下播放按钮,函数“play()”就会执行,然后它会执行 playChosenFile() 和 audioPlayer.play()。
如果我在按下播放按钮之前这样做,音乐播放器会播放歌曲。
如果我在选择要播放的任何文件之前按下播放按钮,程序就会崩溃,因为 musicFilePathURL 为 nil。
如果在按下播放按钮之前没有选择文件,我对如何使程序不崩溃感到困惑。例如,如果你打开 VLC,如果你按下播放按钮,它会提示选择一个文件,但如果你决定按下取消,播放器什么也不做。
如果我按下播放按钮但在启动时没有选择音频文件,如何让我的程序不执行任何操作?
【问题讨论】:
标签: swift macos avaudioplayer