我有一个包含不同场景的 Sprite 套件游戏:主菜单(“MainMenuScene”)和游戏场景(“MyScene”)。当用户在玩游戏时,我有一个没完没了的播放背景音乐。但是当玩家想要停止游戏并返回主菜单时,背景音乐一直在播放。我应该怎么做才能让它停止?我试过 [self removeAllActions] 但没用。
我的场景:
@implementation MyScene
{
SKAction *_backgroundMusic;
}
-(id)initWithSizeCGSize)size {
if (self = [super initWithSize:size]) {
self.backgroundColor = [SKColor colorWithRed:0.15 green:0.5 blue:0.3 alpha:1.0];
}
//Here I make the endless background music
_backgroundMusic = [SKAction playSoundFileNamed"Background 2.m4a" waitForCompletion:YES];
SKAction * backgroundMusicRepeat = [SKAction repeatActionForever:_backgroundMusic];
[self runAction:backgroundMusicRepeat];
return self;
}
- (void)selectNodeForTouchCGPoint)touchLocation
{
SKSpriteNode *touchedNode = (SKSpriteNode *)[self nodeAtPoint:touchLocation];
if ([_MainMenuButton isEqual:touchedNode]) {
SKScene *mainMenuScene = [[MainMenuScene alloc]initWithSize:self.size];
[self.view presentScene:mainMenuScene];
//Here is where the music should stop, when the player presses the 'return to main menu' button
}
}
Best Answer-推荐答案 strong>
我不建议使用 SKAction 播放背景音乐。而是使用 AVAudioPlayer。
使用 AVAudioPlayer:
将 AVFoundation 添加到您的项目中。
#import 到您的 .m 文件中。
在@implementation中添加AVAudioPlayer *_backgroundMusicPlayer;
使用此代码段运行您的音频:
- (void)playBackgroundMusicNSString *)filename
{
NSError *error;
NSURL *backgroundMusicURL = [[NSBundle mainBundle] URLForResource:filename withExtension:nil];
_backgroundMusicPlayer = [[AVAudioPlayer alloc] initWithContentsOfURL:backgroundMusicURL error:&error];
_backgroundMusicPlayer.numberOfLoops = -1;
_backgroundMusicPlayer.volume = 0.8;
_backgroundMusicPlayer.delegate = self;
[_backgroundMusicPlayer prepareToPlay];
[_backgroundMusicPlayer play];
}
还可以阅读 AVAudioPlayer Class Reference这样您就知道所有属性的作用,例如设置音量、循环次数等...
关于ios - 停止 SKAction,我们在Stack Overflow上找到一个类似的问题:
https://stackoverflow.com/questions/23640296/
|