我正在尝试在我的 iOS SpriteKit 应用程序中播放声音,如下所示:
var action = SKAction.PlaySoundFileNamed("filename.wav", false);
SKAction.RunAction(action, "action-name");
已确认声音文件确实存在,否则 PlaySoundFileNamed 会抛出异常。
我还可以确认它正在做某事,因为在第一次执行操作时应用程序会轻微抖动(我知道如何解决这个问题,只是为了确认它做了某事)。
我尝试过的事情:
- 将 PlaySoundFileName
操作上的 waitForCompletion
设置为 true
而不是 false
。
- 调用 AVAudioSession.SharedInstance().SetActive(true, out error)
- 使用.wav 和.m4a 格式的声音。
- 在设备和模拟器上测试。
但是没有声音播放...
有什么想法吗?
最佳答案
仍然没有让它与 Sprite Kit 一起工作,但我通过使用 AVAudioPlayer 解决了它。
public class SoundFile
{
private AVAudioPlayer audioPlayer;
public SoundFile(string fileName)
{
this.FileName = fileName;
}
public string FileName { get; set; }
public bool PreLoaded { get; set; }
public void PreLoad()
{
this.audioPlayer = AVAudioPlayer.FromUrl(new NSUrl(this.FileName));
this.audioPlayer.CurrentTime = 0;
this.audioPlayer.NumberOfLoops = 0;
this.audioPlayer.Volume = 1.0f;
this.audioPlayer.PrepareToPlay();
this.PreLoaded = true;
}
public void Play()
{
if (!this.PreLoaded)
{
this.PreLoad();
}
Task.Run(() =>
{
this.audioPlayer.CurrentTime = 0;
this.audioPlayer.Play();
});
}
}
然后像这样玩:
var sound = new SoundFile("my-filename.wav");
sound.Play();
(显然首先预加载所有声音)
关于ios - SpriteKit 声音不播放,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22664973/