sound effects on/off in spritekit game [closed] - ios

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 8 years ago.
Improve this question
In the gameScene.m how we can make on/off music with skspritenode while playing the game ,with the below code i can play sounds perfectly but i want on/off whenever user wants to on or off the sounds in game to play their own ipad.
//.h file
#import <SpriteKit/SpriteKit.h>
#interface MyScene : SKScene
//.m file
#import "MyScene.h"
#import <AVFoundation/AVAudioPlayer.h>
#interface MyScene() <SKPhysicsContactDelegate>
#end
#import AVFoundation;
#implementation MyScene
{AVAudioPlayer *_AudioPlayer;}
-(void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event {
if (_gameLayer.speed > 0) {
//for flying plane
_playerPlane.physicsBody.velocity = CGVectorMake(0, 0);
[_playerPlane.physicsBody applyImpulse:CGVectorMake(0, 14)];
[self jumpsound];
}
-(void)didBeginContact:(SKPhysicsContact *)contact{
_gameLayer.speed = 0;
[self removeAllActions];
skspritenodeGameOver.hidden = NO;
[self hitSound];}
- (void)jumpsound
{
NSURL *file = [NSURL fileURLWithPath:[[NSBundle mainBundle] pathForResource:#"jump" ofType:#"wav"]];
_AudioPlayer = [[AVAudioPlayer alloc] initWithContentsOfURL:file error:nil];
[_AudioPlayer setVolume:0.5];
[_AudioPlayer play];
}
- (void)hitsound
{
NSURL *file = [NSURL fileURLWithPath:[[NSBundle mainBundle] pathForResource:#"jump" ofType:#"wav"]];
_AudioPlayer = [[AVAudioPlayer alloc] initWithContentsOfURL:file error:nil];
[_AudioPlayer setVolume:0.5];
[_AudioPlayer play];
}
#end

To add sound effects to your game, I suggest using playSoundFileNamed SKAction instead of AVAudioPlayer. Here's an example of how to do that:
#property BOOL playSounds;
// Define action to play a sound effect
_playJumpSound = [SKAction playSoundFileNamed#"jump.wav" waitForCompletion:NO];
// Play sound effect only if playSounds is set
if (_playSounds) {
[self runAction:_playJumpSound];
}
EDIT: Add sounds to methods. Sound will only play if _playSounds == YES.
- (void) playJumpSound
{
if (_playSounds) {
[self runAction:_playJumpSound];
}
}
- (void) playHitSound
{
if (_playSounds) {
[self runAction:_playHitSound];
}
}

Related

Why don't I hear music?

So I have an app where I want to include background music. I use the following code for the music:
.h: (I did also add the framework)
#import <UIKit/UIKit.h>
#import <AVFoundation/AVFoundation.h>
#interface ViewController : UIViewController
{
AVAudioPlayer *player;
}
.m:
- (void)viewDidAppear:(BOOL)animated {
NSURL *url = [[NSBundle mainBundle] URLForResource:#"song" withExtension:#"mp3"];
player = [[AVAudioPlayer alloc] initWithContentsOfURL:url error:nil];
player.numberOfLoops = -1;
[player play];
NSLog(#"playing music");
}
The path for the music file is definitly correct. The app does not crash but I just do not hear any music.
By the way: the LogMessage ("playing music") appears in the debugger.
Any ideas?
Add prepareToPlay method before [player play];
[player prepareToPlay];
Hope this will work...

Background music game play goes right but stop gives an exception

I'm trying to play some music for my game in the background. The music will never stop unless the user turns it off in settings. The music will always play in the background for each view and doesn't pause or something.
For this reason I've made a singleton class for my background music. But when I press "Stop the music", the app breakpoints for an exception (I'm not seeing one, so I don't know what's wrong).
The music still stops, but there is something wrong and I don't know what. Is it right to make it in a singleton class, or do I need to solve this on an other way?
Here is a screenshot of when the exception happens:
Here is the code for my singleton class:
#import <Foundation/Foundation.h>
#import <AVFoundation/AVFoundation.h>
#interface Music : NSObject
#property AVAudioPlayer *player;
- (void)stop;
- (void)play;
+ (Music *)sharedInstance;
#end
#import "Music.h"
#implementation Music
+ (Music *)sharedInstance {
static Music *sharedInstance;
static dispatch_once_t onceToken;
dispatch_once(&onceToken,^{
sharedInstance = [[Music alloc] init];
});
return sharedInstance;
}
-(instancetype)init{
self = [super init];
if (self) {
NSURL *url = [NSURL fileURLWithPath:[[NSBundle mainBundle]
pathForResource:#"water_2"
ofType:#"wav"]];
self.player = [[AVAudioPlayer alloc] initWithContentsOfURL:url error:nil];
self.player.numberOfLoops = -1;
}
return self;
}
- (void)stop{
[self.player stop];
}
- (void)play{
[self.player play];
}
I would switch up your code and I would use an IBAction instead of void stop and void play
-(IBAction)stop {
[player stop];
}
-(IBAction)play {
[player play];
}

How to play audio file on app startup [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 9 years ago.
Improve this question
I want to play a sound at app startup, and then give the user the chance to pause the sound through a "stop" button. How can I do that?
My actual code is:
player1 = [[AVAudioPlayer alloc]
initWithContentsOfURL:[NSURL fileURLWithPath:
[[NSBundle mainBundle] pathForResource:#"Startsound" ofType:#"m4a"]]error:nil];
player1.numberOfLoops=-1;
[player1 prepareToPlay];
As twisted this question was, I did get he was trying to say.
This is how you do it. In your v1AppDelegate.h file add
#import <UIKit/UIKit.h>
#import <AVFoundation/AVFoundation.h>
#include <AudioToolbox/AudioToolbox.h>
#interface v1AppDelegate : UIResponder <UIApplicationDelegate>
{
AVAudioPlayer *myAudioPlayer;
}
#property (nonatomic, retain) AVAudioPlayer *myAudioPlayer;
#property (strong, nonatomic) UIWindow *window;
#end
Now in your v1AppDelegate.m file add this
#import "v1AppDelegate.h"
#import <AVFoundation/AVFoundation.h>
#include <AudioToolbox/AudioToolbox.h>
#implementation v1AppDelegate
#synthesize window = _window;
#synthesize myAudioPlayer;
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
//start a background sound
NSString *soundFilePath = [[NSBundle mainBundle] pathForResource:#"Startsound" ofType: #"m4a"];
NSURL *fileURL = [[NSURL alloc] initFileURLWithPath:soundFilePath ];
myAudioPlayer = [[AVAudioPlayer alloc] initWithContentsOfURL:fileURL error:nil];
myAudioPlayer.numberOfLoops = -1; //infinite loop
[myAudioPlayer play];
// Override point for customization after application launch.
return YES;
}
If you wish to stop or start this music from anywhere else in your code then simply add this
#import "v1AppDelegate.h"
- (IBAction)stopMusic
{
v1AppDelegate *appDelegate = [[UIApplication sharedApplication] delegate];
[appDelegate.myAudioPlayer stop];
}
- (IBAction)startMusic
{
v1AppDelegate *appDelegate = [[UIApplication sharedApplication] delegate];
[appDelegate.myAudioPlayer play];
}

playing a mp3 file in iOS app [duplicate]

This question already has answers here:
How do I programmatically play an MP3 on an iPhone?
(4 answers)
Closed 4 years ago.
I can't figure out how to play a music file in an iPhone game.
Im creating a Game and I am trying to figure out how to play music whenever the app is launched.
I tried this:
- (void)awakeFromNib {
NSString *path = [[NSBundle mainBundle] pathForResource:#"musicamenu" ofType:#"mp3"];
AVAudioPlayer *theAudio = [[AVAudioPlayer alloc] initWithContentsOfURL:[NSURL fileURLWithPath:path] error:NULL];
[theAudio play];
}
This is how you do it. In your v1AppDelegate.h file add
#import <UIKit/UIKit.h>
#import <AVFoundation/AVFoundation.h>
#import <AudioToolbox/AudioToolbox.h>
#interface v1AppDelegate : UIResponder <UIApplicationDelegate>
{
AVAudioPlayer *myAudioPlayer;
}
#property (nonatomic, retain) AVAudioPlayer *myAudioPlayer;
#property (strong, nonatomic) UIWindow *window;
#end
Now in your v1AppDelegate.m file add this
#import "v1AppDelegate.h"
#import <AVFoundation/AVFoundation.h>
#import <AudioToolbox/AudioToolbox.h>
#implementation v1AppDelegate
#synthesize window = _window;
#synthesize myAudioPlayer;
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
//start a background sound
NSString *soundFilePath = [[NSBundle mainBundle] pathForResource:#"Soothing_Music2_Long" ofType: #"mp3"];
NSURL *fileURL = [[NSURL alloc] initFileURLWithPath:soundFilePath ];
myAudioPlayer = [[AVAudioPlayer alloc] initWithContentsOfURL:fileURL error:nil];
myAudioPlayer.numberOfLoops = -1; //infinite loop
[myAudioPlayer play];
// Override point for customization after application launch.
return YES;
}
If you wish to stop or start this music from anywhere else in your code then simply add this
#import "v1AppDelegate.h"
- (IBAction)stopMusic
{
v1AppDelegate *appDelegate = [[UIApplication sharedApplication] delegate];
[appDelegate.myAudioPlayer stop];
}
- (IBAction)startMusic
{
v1AppDelegate *appDelegate = [[UIApplication sharedApplication] delegate];
[appDelegate.myAudioPlayer play];
}
I recommend to add the play music method in applicationDidBecomeActive: method. Because you want the music played every time the app is launched. Note you should hold a reference to the player. Else the music will not be played.
- (void)applicationDidBecomeActive:(UIApplication *)application
{
// Play music on another queue so that the main queue is not blocked.
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
[self playMusic];
});
}
- (void)playMusic
{
NSString *path = [[NSBundle mainBundle] pathForResource:#"done" ofType:#"mp3"];
NSError *error = nil;
NSURL *url = [NSURL fileURLWithPath:path];
self.player = [[AVAudioPlayer alloc] initWithContentsOfURL:url error:&error];
[self.player play];
}
For Swift 3.1 :
Use this two imports :
import AVFoundation
import AudioToolbox
Create a reference for your AVAudioPlayer :
private var mAudioPlayer : AVAudioPlayer?
Use this function for play a sound you are storing in your app :
func onTapSound(){
let soundFile = Bundle.main.path(forResource: "slap_placeholder.wav", ofType: nil)
let url = URL(fileURLWithPath: soundFile!)
self.mAudioPlayer = try! AVAudioPlayer(contentsOf: url as URL)
self.mAudioPlayer?.play()
}

Play MP3 Files with iPhone SDK [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 4 years ago.
Improve this question
What's the easiest way to play a music file such as Mp3 with pause button?
very very simple a button play and another button pause that music
These are the codes for the requested actions,
appSoundPlayer is a property of AVAudioPlayer declared in h file. Also this example plays a song in the resource folder.
#pragma mark -
#pragma mark *play*
- (IBAction) playaction {
NSString *soundFilePath = [[NSBundle mainBundle] pathForResource:#"songname" ofType:#"mp3"];
NSURL *newURL = [[NSURL alloc] initFileURLWithPath: soundFilePath];
self.soundFileURL = newURL;
[newURL release];
[[AVAudioSession sharedInstance] setDelegate: self];
[[AVAudioSession sharedInstance] setCategory: AVAudioSessionCategoryAmbient error: nil];
// Registers the audio route change listener callback function
AudioSessionAddPropertyListener (
kAudioSessionProperty_AudioRouteChange,
audioRouteChangeListenerCallback,
self
);
// Activates the audio session.
NSError *activationError = nil;
[[AVAudioSession sharedInstance] setActive: YES error: &activationError];
AVAudioPlayer *newPlayer = [[AVAudioPlayer alloc] initWithContentsOfURL: soundFileURL error: nil];
self.appSoundPlayer = newPlayer;
[newPlayer release];
[appSoundPlayer prepareToPlay];
[appSoundPlayer setVolume: 1.0];
[appSoundPlayer setDelegate: self];
[appSoundPlayer play];
[stopbutton setEnabled:YES];
[playbutton setEnabled: NO];
playbutton.hidden=YES;
pausebutton.hidden =NO;
}//playbutton touch up inside
#pragma mark -
#pragma mark *pause*
-(IBAction)pauseaction {
[appSoundPlayer pause];
pausebutton.hidden = YES;
resumebutton.hidden = NO;
}//pausebutton touch up inside
#pragma mark -
#pragma mark *resume*
-(IBAction)resumeaction{
[appSoundPlayer prepareToPlay];
[appSoundPlayer setVolume:1.0];
[appSoundPlayer setDelegate: self];
[appSoundPlayer play];
playbutton.hidden=YES;
resumebutton.hidden =YES;
pausebutton.hidden = NO;
}//resumebutton touch up inside
#pragma mark -
#pragma mark *stop*
-(IBAction)stopaction{
[appSoundPlayer stop];
[playbutton setEnabled:YES];
[stopbutton setEnabled:NO];
playbutton.hidden=NO;
resumebutton.hidden =YES;
pausebutton.hidden = YES;
}//stopbutton touch up inside
For short sounds or when the MP3 does not play well on the suggested code you can always use:
SystemSoundID soundID;
NSURL *url = [NSURL fileURLWithPath:[NSString stringWithFormat:#"%#/sound.mp3", [[NSBundle mainBundle] resourcePath]]];
AudioServicesCreateSystemSoundID((CFURLRef)url, &soundID);
AudioServicesPlaySystemSound (soundID);
Don't forget to add:
#import <AudioToolbox/AudioToolbox.h>
well here is a good tutorial available.
The theme is
NSURL *url = [NSURL fileURLWithPath:[NSString stringWithFormat:#"%#/audiofile.mp3", [[NSBundle mainBundle] resourcePath]]];
NSError *error;
AVAudioPlayer *audioPlayer = [[AVAudioPlayer alloc] initWithContentsOfURL:url error:&error];
audioPlayer.numberOfLoops = -1;
[audioPlayer play];
and when you want to pause;
[audioPlayer pause];
hope this helps.
I'm afraid the answer stated no longer works in iOS 7 and above. You will need to use the following code:
in the header file (.h)
In order to handle the delegate methods like when the playing of the audio has finished audioPlayerDidFinishPlaying:, inherit from AVAudioPlayerDelegate .
#property (nonatomic, strong) AVAudioPlayer *player;
in the implementation file (.m)
NSString *soundFilePath = [[NSBundle mainBundle] pathForResource: resourceName
ofType: #"mp3"];
NSURL *fileURL = [[NSURL alloc] initFileURLWithPath: soundFilePath];
AVAudioPlayer *newPlayer = [[AVAudioPlayer alloc] initWithContentsOfURL: fileURL
error: nil];
_player = newPlayer;
[_player prepareToPlay];
[_player setDelegate: self];
[_player play];
I like simple code and here is my solution : (Remember to add switch button to get music play. Have fun)
#import "ViewController.h"
#import <AVFoundation/AVFoundation.h>
#interface ViewController ()
{
NSURL* bgURL;
AVAudioPlayer* bgPlayer;
}
#end
#implementation ViewController
- (void)viewDidLoad {
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
bgURL = [[NSURL alloc] initFileURLWithPath: [[NSBundle mainBundle] pathForResource:#"sample" ofType:#"mp3"]];
bgPlayer = [[AVAudioPlayer alloc] initWithContentsOfURL:bgURL error:nil];
}
#pragma mark AVAudioPlayer
- (IBAction)toggleMusic:(UISwitch*)sender {
NSLog(#"togging music %s", sender.on ? "on" : "off");
if (bgPlayer) {
if (sender.on) {
[bgPlayer play];
}
else {
[bgPlayer stop];
}
}
}
The Apple documentation here should have everything you need to know.
DIRAC API is free and quite easy to use.
We've used it in my talking robot app http://itunes.apple.com/us/app/daidai/id484833168 and it has been amazing to me how it manages to change the speed and pitch of voice
http://www.dspdimension.com/download/
The oalTouch sample code on the Apple iOS developer web site does what you want, and is ready to run.
It also shows how to test if another app (eg ipod) is playing a file already, which is handy if you want to allow your users to listen to their own music instead of yours.

Resources