简体   繁体   English

调节SKAction的音量playSoundFileNamed:

[英]Regulating the volume of SKAction playSoundFileNamed:

Is there a way to regulate the volume of sound played via SKAction playSoundFileNamed:waitForCompletion: . 有没有办法调节通过SKAction playSoundFileNamed播放的声音音量:waitForCompletion : .

I would like to implement a simple music & sound effects slider in my game. 我想在我的游戏中实现一个简单的音乐和声音效果滑块。 I can easily control background music since i play it via AVAudioPlayer, but all sound effects are played via SKAction. 我可以通过AVAudioPlayer轻松控制背景音乐,但所有音效都通过SKAction播放。

Here is my code for how i handled this problem 这是我如何处理这个问题的代码

NSError *error;
NSURL *soundURL = [[NSBundle mainBundle] URLForResource:@"pew-pew-lei" withExtension:@"caf"];
AVAudioPlayer *player = [[AVAudioPlayer alloc] initWithContentsOfURL:soundURL error:&error];
[player setVolume:masterVolume];
[player prepareToPlay];

SKAction*   playAction = [SKAction runBlock:^{
    [player play];
}];
SKAction *waitAction = [SKAction waitForDuration:player.duration+1];
SKAction *sequence = [SKAction sequence:@[playAction, waitAction]];

[self runAction:sequence];

The masterVolume variable is just some preset variable i have that the user can change from 0.0-1.0 masterVolume变量只是一些预设变量,用户可以从0.0-1.0更改

The waitAction ensures that the player doesn't get removed before it has played the entire sound waitAction确保播放器在播放整个声音之前不会被删除

Hope this helps! 希望这可以帮助!

Unfortunately you can't modify the volume using SKAction, so you have to use AVAudioPlayer for your effects too. 遗憾的是,您无法使用SKAction修改音量,因此您也必须使用AVAudioPlayer作为效果。 You could implement a custom playSoundFileNamed:waitForCompletion:volume: using runBlock as you already thought, so your code won't be very different then using playSoundFileNamed:waitForCompletion:. 你可以实现一个自定义的playSoundFileNamed:waitForCompletion:volume:正如你所想的那样使用runBlock,所以你的代码与使用playSoundFileNamed:waitForCompletion:的差别不大。

Swift: 迅速:

Since iOS 9.0 you can change the volume to your node running another action if you have already runned your audio ( remember that this one obviusly cannot work if you have something that run with repeatForever ): iOS 9.0开始 ,如果您已经运行了音频,则可以将音量更改为运行其他操作的节点( 请记住,如果您有使用repeatForever运行的内容,那么这个音频repeatForever ):

let changeVolumeAction = SKAction.changeVolume(to: 0.3, duration: 0.3)
node.run(changeVolume)

Or you can create a group and launching your audio with the correct volume: 或者您可以创建一个组并使用正确的音量启动音频:

let effectAudioAction = SKAction.playSoundFileNamed("electricshockLow.mp3", waitForCompletion: false)
let changeVolumeAction = SKAction.changeVolume(to: 0.3, duration: 0.3)
let effectAudioGroup = SKAction.group([effectAudioAction,changeVolumeAction])
node.run(effectAudioGroup)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM