首页 > 解决方案 > 在 Xcode 的目录中找不到媒体文件

问题描述

我试图简单地播放 MP3 声音(我已将其包含在“文件”文件夹下的项目目录中)。这是我使用的片段:

import Foundation
import AVFoundation
import Cocoa
import Speech


var sound = AVAudioPlayer()
let path = Bundle.main.path(forResource: "this", ofType: "mp3")

do {
    sound = try AVAudioPlayer(contentsOf: URL(fileURLWithPath: path!)) //line 19
}
catch {
    print("ERROR")
}
sound.play()

文件名为“this.mp3”。问题出现在第 19 行,错误为“致命错误:在展开可选值时意外发现 nil:文件”我读到了这个错误,所以我认为我的程序无法找到该文件。

任何帮助,将不胜感激。

标签: iosswiftxcodemacoscommand-line

解决方案


编辑 3

在评论澄清后,OP正在编写Command Line Application...

确保您的音频文件包含如下:

在此处输入图像描述

然后,(非常简化的)示例测试代码可以是:

import Foundation
import AVFoundation

class AudioTest {

    var sound = AVAudioPlayer()

    func testMP3() -> Void {

        let bundle = Bundle.main
        let url = bundle.url(forResource: "files/this", withExtension: "mp3")
        if let u = url {

            do {
                sound = try AVAudioPlayer(contentsOf: u, fileTypeHint: AVFileType.mp3.rawValue)
                sound.prepareToPlay()
                sound.play()
            } catch let error {
                print(error.localizedDescription)
            }

        } else {
            print("Could not find resource!")
        }

    }

}   

我在这里建立了一个完整(简单)的示例项目:https ://github.com/DonMag/TestMP3


以下内容基于 iOS 应用程序中的使用情况

确保您的AVAudioPlayer对象未在您尝试播放声音的位置声明。它会在实际播放音频之前超出范围。

以下是当前播放声音的方式,例如点击按钮:

// declared at class-level
var sound = AVAudioPlayer()

@IBAction func didTap(_ sender: Any) {

    // abort with error message if this.mp3 is not found in the bundle
    guard let url = Bundle.main.url(forResource: "this", withExtension: "mp3") else {
        fatalError("Could not get URL for mp3 file!")
    }

    do {
        try AVAudioSession.sharedInstance().setCategory(.playback, mode: .default)
        try AVAudioSession.sharedInstance().setActive(true)

        sound = try AVAudioPlayer(contentsOf: url, fileTypeHint: AVFileType.mp3.rawValue)

        sound.play()

    } catch let error {
        print(error.localizedDescription)
    }

}

编辑

如果此代码停止并打印Could not get URL for mp3 file!到调试控制台,则您的 mp3 文件包含在包中。

在 Project Navigator 中选择它,并确保它在 File Inspector 窗格中选中了您的目标Target Membership另请检查:

  • 项目设置
  • 构建阶段
  • 复制捆绑资源

并确保它列在那里。


编辑 2

假设您在模拟器上运行它...

在之前添加这两行guard let url - ...

let path = Bundle.main.path(forResource: "Info", ofType: ".plist")
print(path)

这应该会打印出一条看起来像这样的长路径:

/Users/yourname/Library/Developer/CoreSimulator/Devices/C55189E0-FDC2-4D93-A1DA-D52EF2EAE905/data/Containers/Bundle/Application/F50C01D1-FF99-4592-8569-120E7362E23B/xcodeProject.app/Info.plist

复制该路径,转到 Finder 窗口,选择Go -> Go to Folder...并粘贴整个路径。查看那里找到的文件,看看你是否this.mp3存在。

如果没有,this.mp3请从您的项目中删除并重新添加,然后再试一次。


推荐阅读