【问题标题】:Can't access local resource with NSURL. Strange无法使用 NSURL 访问本地资源。奇怪的
【发布时间】:2013-10-04 12:33:55
【问题描述】:

我的 iOS 应用想要播放本地音频文件。所以,在 xCode 中,我在我的项目中添加了一个文件“audio.m4a”。它位于文件树的顶层,但是

    NSURL *audioFileURL = [[NSBundle mainBundle] 
URLForResource:@"audio" 
withExtension:@"m4a"];

返回nil。一定有一个愚蠢的疏忽。 我做错了什么?

【问题讨论】:

    标签: xcode nsbundle


    【解决方案1】:
    NSBundle *mainBundle = [NSBundle mainBundle];
    NSString *myFile = [mainBundle pathForResource: @"audio" ofType: @"m4a"];
    NSURL *audioFileURL = [NSURL URLWithString:myFile];
    

    并检查该文件是否存在于Build Phases" -> "copy bundle Resources"

    【讨论】:

    • "...并检查该文件是否存在于构建阶段..." 成功了。我知道这是一件愚蠢的事情。今天我了解到:如果您将图像添加到项目中,它会自动复制到您的 app.bundle 中。如果添加声音文件,则不然。
    • 此代码错误。 -pathForResource:…-URLForResource:… 之间的文件行为没有区别。更重要的是,+URLWithString: 是完全错误的从文件路径创建 URL 的方法
    【解决方案2】:

    斯威夫特

    由于这两个答案都不完整,并且解决方案已在 cmets 中传播,让我提供一个 Swift 替代方案。和一步一步的回应。

    原来的Objective-C代码是正确的:

    NSURL *audioFileURL = [[NSBundle mainBundle] 
        URLForResource:@"audio" 
        withExtension:@"m4a"];
    

    斯威夫特

    let audioFileURL = NSBundle.mainBundle().URLForResource(
        "audio",
        withExtension: "m4a")
    

    目标会员

    这可能是最初将资源添加到项目时的疏忽。添加这些文件时,您必须选择足够的目标:

    不管是什么语言,确保您的文件是Project > Build Phases > Copy Bundle Resources。您无需手动执行此操作。相反,请使用 文件检查器。选择您的资源(在左侧面板上)并验证它的目标成员身份(在右侧面板上):

    【讨论】:

      【解决方案3】:
      /* Use this code to play an audio file */
      NSString *soundFilePath = [[NSBundle mainBundle] pathForResource:@"test" ofType:@"m4a"];
      NSURL *soundFileURL = [NSURL fileURLWithPath:soundFilePath];
      
      AVAudioPlayer *player = [[AVAudioPlayer alloc] initWithContentsOfURL:soundFileURL error:nil];
      player.numberOfLoops = -1; //Infinite
      
      [player play];
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2012-09-09
        • 2012-06-22
        • 2013-07-16
        • 1970-01-01
        相关资源
        最近更新 更多