ios - 摇晃播放我的阵列列表中的随机歌曲时出现异常

标签 ios audio shake

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

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

任何帮助将不胜感激

最佳答案

等待。您说过将文件放在音乐文件夹中?那么您的代码是错误的。您发布的代码尝试从您的应用程序包内部读取文件。您需要完全使用另一种方法来从用户的音乐文件夹中读取文件,并且需要编写该代码以检查文件是否存在,如果不存在则正常失败。

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

关于ios - 摇晃播放我的阵列列表中的随机歌曲时出现异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47847470/

相关文章:

ios - 水平翻转视频如果这样则没有镜像效果

ios - 如何将 "yyyy-MM-dd HH:mm:ss +0000"转换为日期?

ios - iOS Safari音频流播放问题

c# - 摇动动画(3d版)

ios - 如何让 UIButton 在点击时摇动?

android - 有没有一种稳定的方法来检测震动事件?

ios - iOS应用提交备忘单

IOS 警告 : Unable to allocate render buffer storage

c# - 听WaveOutDevice

c++ - 在 C++ 中检测视频是否没有音频,最好使用 Qt Phonon