在摇动时从我的阵列列表中播放随机歌曲时出现异常

问题描述 投票:0回答:1

我正在开发一个应用程序,它可以播放设备震动中的随机歌曲。以下是我的代码

import UIKit
import AVFoundation

class ViewController: UIViewController {
    var player = AVAudioPlayer()

    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view, typically from a nib.
    }

    override func motionEnded(_ motion: UIEventSubtype, with event: UIEvent?) {
        if event?.subtype == UIEventSubtype.motionShake{
            let soundArray=["firstsong","second","fourth"]
            let randomNumber=Int(arc4random_uniform(UInt32(Int32(soundArray.count))))

            let fileLocation = Bundle.main.path(forResource: soundArray[randomNumber], ofType: "mp3")
            do {
                try player=AVAudioPlayer(contentsOf:URL(fileURLWithPath:fileLocation!))
                player.play()
            }catch{

            }
        }
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }


}

我把我的mp3文件放在音乐文件夹中。当我摇动设备时,我收到以下错误

Thread 1: Fatal error: Unexpectedly found nil while unwrapping an Optional value

任何帮助将不胜感激

ios audio shake
1个回答
0
投票

等待。你说你把文件放在音乐文件夹中?那你的代码错了。您发布的代码会尝试从您的应用包中读取文件。您需要完全使用不同的方法来读取用户音乐文件夹中的文件,并且需要编写该代码以检查文件是否存在,如果不存在则优先失败。

我建议将您的声音文件拖到Xcode中项目的“resources”文件夹中,并确保选中文件的复选框,以便它们包含在您的应用程序包中。如果你这样做你的代码应该工作(但是你仍然应该检查nil而不是使用force unwrapping,正如我在上面的评论中提到的那样。)

© www.soinside.com 2019 - 2024. All rights reserved.