我有一个带有不同场景的精灵套件游戏:主菜单("MainMenuScene")和游戏场景("MyScene")。当用户在玩游戏的时候,我有一个无穷无尽的背景音乐。但是当玩家想要停止游戏并返回主菜单时,背景音乐就会继续播放。我该怎么做才能让它停下来?我试过[self removeAllActions],但没有成功。
MyScene:
@implementation MyScene
{
SKAction *_backgroundMusic;
}
-(id)initWithSize:(CGSize)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)selectNodeForTouch:(CGPoint)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
}
}发布于 2014-05-14 15:25:14
我不建议使用SKAction播放背景音乐。相反,请使用AVAudioPlayer。
要使用AVAudioPlayer:
#import <AVFoundation/AVFoundation.h>进入您的.m文件。AVAudioPlayer *_backgroundMusicPlayer;使用此代码片段运行音频:
- (void)playBackgroundMusic:(NSString *)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类引用,以便您了解所有属性所做的事情,如设置卷、循环数等。
发布于 2014-05-13 20:08:07
试着用这个播放音乐:
[self runAction:backgroundMusicRepeat withKey:@"bgmusic"];这是为了阻止:
[self removeActionForKey:@"bgmusic"];更新
SKAction * backgroundMusicRepeat = [SKAction playSoundFileNamed:@"Background 2.m4a" waitForCompletion:YES];
backgroundMusicRepeat = [SKAction repeatActionForever:backgroundMusicRepeat];
[self runAction:backgroundMusicRepeat];我已经在我自己的项目中运行了这些代码,并且看起来很有用。但不是你的方式,只有当我退出视图时,它才会停止,我甚至不需要removeActionForKey。[self removeActionForKey:@"bgmusic"];不会在现场工作的。
因此,如果您想在同一视图的不同场景之间切换时停止声音,我建议您使用AVAudioPlayer。
我还发现堆栈溢出中的其他一些问题与您的问题相同,比如:如何在使用SpriteKit时暂停声音和Spritekit停止声 --它们都支持AVAudioPlayer。
正如这些链接中的评论之一:,您应该使用playSoundFileNamed方法来播放声音效果.一些短短的1或2秒,比如爆炸声--不要用它来做背景音。
https://stackoverflow.com/questions/23640296
复制相似问题