【问题标题】:AVFoundation not playing audio files in SpriteKitAVFoundation 不在 SpriteKit 中播放音频文件
【发布时间】:2014-06-24 11:10:22
【问题描述】:

我已经阅读了 raywenderlich.com 上的所有 SpriteKit 教程,并且在每个教程中都可以使用,除了音频。我无法在任何教程中获得任何音效。比如本教程http://www.raywenderlich.com/49697/sprite-kit-tutorial-making-a-universal-app-part-2,我将声音文件复制到我的项目中,然后

1) 将 AVFoundation 导入 MyScene.h

#import <AVFoundation/AVFoundation.h>

2) 在 MyScene.h 中添加了三个属性

@property (strong, nonatomic) AVAudioPlayer *audioPlayer;
@property (strong, nonatomic) SKAction *laughSound;
@property (strong, nonatomic) SKAction *owSound;

3) MyScene.m 中 initWithSize 中预加载音效

// Add at the bottom of your initWithSize: method
// Preload whack sound effect
self.laughSound = [SKAction playSoundFileNamed:@"laugh.caf" waitForCompletion:NO];
self.owSound = [SKAction playSoundFileNamed:@"ow.caf" waitForCompletion:NO];

NSURL *url = [[NSBundle mainBundle] URLForResource:@"whack" withExtension:@"caf"];
NSError *error = nil;
self.audioPlayer = [[AVAudioPlayer alloc] initWithContentsOfURL:url error:&error];

if (!self.audioPlayer) {
    NSLog(@"Error creating player: %@", error);
}

[self.audioPlayer play];

4) 以两种不同的方法将声音动作添加到序列中

// Add at bottom of popMole method, change the sequence action to:
SKAction *sequence = [SKAction sequence:@[easeMoveUp, setTappable, self.laughSound, self.laughAnimation, unsetTappable, easeMoveDown]];

// Add inside touchesBegan: method, change the sequence action to:
SKAction *sequence = [SKAction sequence:@[self.owSound, self.hitAnimation, easeMoveDown]];

谁能解释为什么我在设备上运行代码时可能没有播放声音?请注意,当我制作常规 iOS 应用程序(没有 SpriteKit)时,我已经能够毫无问题地使用 AVFoundation。

更新

正如第一条评论中所建议的,我单独使用 skaction 运行了一个声音文件,但它没有播放声音。日志语句每次应该运行时都会运行

 SKAction *sound = [SKAction playSoundFileNamed:@"laugh.caf" waitForCompletion:NO];
 NSLog(@"run sound");
 [self runAction:sound];

【问题讨论】:

  • 我猜这是实际的声音文件本身。获取一个苹果系统的 .aiff 声音文件并尝试播放这些文件,以确保声音导出没有什么奇怪的地方。查看我的 AVAudioPlayer 管理器,我也有#import &lt;AudioToolbox/AudioServices.h&gt;,我认为它是更改 AVAudioPlayer 对象上的音量所必需的。您是否在项目的其他地方对 AVAudioSession 做了任何可能导致问题的事情?
  • @CHBuckingham 当我在 xcode 中单击声音文件(在此项目中为 .caf)时,它们会在带有音频播放器的新窗口中打开并且播放正常。我没有对 AVAudioSession 做任何事情。这只是我正在关注的一个简单教程。然而,正如 OP 中提到的,我已经完成了多个带有音频的 SpriteKit 教程并且总是相同的结果(没有声音),即使我已经制作了非 SpriteKit ios 项目,这些项目可以使用 AVAudioPlayer 完美播放音频。
  • 用法令人困惑,我不确定您为什么同时使用 SKActions 和 AVAudioPlayer 的实例。这使我认为您可能正在组合教程代码?我会按照我在第一条评论中的建议进行操作,通过 SKAction 播放系统声音文件,以确保它不是导出设置,这是大多数情况下的情况。
  • @CHBuckingham 抱歉,我想我误解了您的第一条评论。我现在尝试了(请参阅 OP 中的更新),但没有播放声音。我不认为我在混合教程代码(OP 中的链接)。这是我在他们网站上完成的每个 SpriteKit 教程都会发生的事情。

标签: ios objective-c


【解决方案1】:

如果声音文件不通过 SKAction 播放,但相同的声音文件确实通过非精灵套件项目中的 AVAudioPlayer 播放,那么它几乎总是三件事之一:

  1. 在场景层级中播放动作的不是子级。
  2. 限制性更强的 SKAction 不支持声音文件的文件格式/导出设置。
  3. AVAudiOSession 共享实例设置不正确。

没有看到项目的所有代码,我还是赌1还是2。

【讨论】:

    猜你喜欢
    • 2017-08-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-09-09
    • 2020-02-11
    • 2021-05-19
    • 1970-01-01
    相关资源
    最近更新 更多