Background Music causes crash in XCode - sprite-kit

I am trying to play my music within my game app and it crashes. But when I copy and paste the code within a different xcode project it works?
I'm using a 2d game engine called SpriteKit within Xcode. I play an mp3 file using the AVFoundation framework.
NSURL *url = [[NSBundle mainBundle] URLForResource:#"backgroundMusic" withExtension:#"mp3"];
self.backgroundMusic = [[AVAudioPlayer alloc] initWithContentsOfURL:url error:nil];
self.backgroundMusic.numberOfLoops = 1;
[self.backgroundMusic prepareToPlay];
[self.backgroundMusic play];

AVAudioPlayer throws breakpoint in debug mode
I've had this problem before, this answer helped me:
"Add your exception breakpoint and edit the exception type from "All" to "Objective-C exceptions"
Some classes in AudioToolbox throw regular C++ exceptions. You can filter them off this way."

Related

No sound in iPhone simulator for XCode 4.6.3

I have tried several options (many of them referenced from this post on SO and elsewhere) to get music to play on the iPhone simulator, but so far none of it has worked. I have tried -
Unchecking, and then checking the box that says "Player user interface sound effects" in the Preferences > Sound option
Going to Audio Midi Set Up, and changing the sample rate to 44100
Ensuring that the output/input is both using the internal speakers
Make sure that I imported <AVFoundation/AVFoundation.h> and added the AVFoundation.framework to my linked frameworks.
Resetting iOS simulator using Reset Settings/Contents
Restarting XCode, as well as as the computer
I have the following code in viewDidLoad that is play the file gundam.mp3
NSString *soundFilePath = [[NSBundle mainBundle] pathForResource:#"gundam" ofType:#"mp3"];
NSURL *soundFileURL = [NSURL fileURLWithPath:soundFilePath];
AVAudioPlayer *player = [[AVAudioPlayer alloc] initWithContentsOfURL:soundFileURL error:nil];
player.numberOfLoops = 1;
player.volume = 0.9;
NSLog(#"The sound URL is %#", soundFileURL);
[player play];
The NSLog seems to be able to capture the file correctly: The sound URL is file://localhost/Users/zallanx/Library/Application%20Support/iPhone%20Simulator/6.1/Applications/[...]/Missile%20Defender.app/gundam.mp3
I am unsure what I am doing incorrectly based on all the options I have tried, and would appreciate your help. Thanks!

iOS record video and play MP3 at the same time

I need to record video from the iPhone camera, and play an MP3 file at the same time.
I started with AVCam sample code, which I'm sure you all have. It works great for recording video.
However, I then added the following code to play an MP3. This MP3-playing code works in a different app of mine, but when I insert it into this sample code the MP3 not only does not play, the AVCamCaptureManager's recordingDidFinishToOutputFileURL never gets called, so the video never gets saved out.
It's like the audio playing code conflicts with the video capture code. Any ideas?
Here's the audio playing code I put into AVCam:
AVAudioPlayer *audioPlayer = nil;
NSURL *url = [NSURL fileURLWithPath:[NSString stringWithFormat:#"%#/soundeffect.mp3", [[NSBundle mainBundle] resourcePath]]];
audioPlayer = [[AVAudioPlayer alloc] initWithContentsOfURL:url error:&error];
[audioPlayer setVolume:1.0];
[audioPlayer prepareToPlay];
[m_audioPlayer play];
Pretty simple code here. Not sure why this audio playing code causes recordingDidFinishToOutputFileURL to never get called...
Thanks for any ideas.
I figured it out: I just had to remove some code within AVCam that allocated AVCaptureDeviceInput - audioInput. That was unnecessary and conflicted with my audio playback code.

Couldn't play system sound after switching to iOS 5

This is how I played a beep sound effect in iOS 4:
SystemSoundId beepOnSoundId;
CFURLRef soundUrl = CFBundleCopyResourceURL(
CFBundleGetMainBundle(),
CFSTR("beep"),
CFSTR("wav"),
NULL
);
// soundUrl logged:
// file://localhost/var/mobile/Applications/ ... beep.wav
AudioServicesCreateSystemSoundID(soundUrl, &beepOnSoundId);
// beepOnSoundId logged: 4097
AudioServicesPlaySystemSound(beepOnSoundId);
It stopped working, when I upgraded my device to iOS 5. I hear nothing. I logged out all the variables and none were nil or 0.
How has the API changed in iOS 5 that breaks my sound playing code?
Update
The problem may be because I have an AVCaptureSession running while I play the sound. iOS 5 somehow doesn't let you do this anymore. I need to play a beep sound while I am recording something from the camera.
This bug report could be related to your question, if you have an AVCaptureSession running.
Under iOS 5, when using an AudioServicesPlaySystemSound call, it will
not work when there is an active AVCaptureSession with an audio device
active.
One problem could be that in ios 5 when you call AudioServicesPlaySystemSound, it stop working if there is an active AVCaptureSession with an audio device active.
Also check the names of imports in your files, make sure the audiotoolbox import is in all your viewcontrollers.
I also went to a guide and got this for you :) I'll leave the website's name at the bottom
Step 1: Import the AudioToolbox Framework
Begin by importing the Audio Toolbox framework into your application in order to make the System Sound Services available to your code. To do so, select the “PhoneAppSkin” project in the Project Navigator pane in Xcode, then select “PhoneAppSkin” under “TARGETS”, and finally select the “Build Phases” tab. After doing so, your screen should look something like this:
Next, click the “Link Binary With Libraries” drop down, and click the “+” symbol to add a new framework to our project’s linking phase.
Finally, find the “AudioToolbox” framework in the popup window, and then click “Add”.
Next, open up the PhoneViewController.h file and add the line necessary to actually import the Audio Toolbox framework into your class:
#import <UIKit/UIKit.h>
#import <AudioToolbox/AudioToolbox.h>
The Audio Toolbox functions should now work
Website I got the images from: http://mobile.tutsplus.com/tutorials/iphone/ios-sdk_playing-systemsoundid/
I have almost the same code and it works for me in iOS5 with a video and an audio media sessions on. If you have all the code in a function to play the sound the problem may be that the SystemSoundID object gets deallocated before the sound can be played, or the problem may be with the URL. But I guess it is the first one.
See, the following code works:
The SystemSoundID declaration is in the header of the object and the object lives long enough to play the sound.
SystemSoundID soundID;
The AudioServicesCreateSystemSoundID is in the object initialization.
AudioServicesCreateSystemSoundID((CFURLRef)[NSURL fileURLWithPath:[[NSBundle mainBundle]
pathForResource: #"sound" ofType:#"wav"]], &soundID);
Then you can use AudioServicesPlaySystemSound wherever you want inside the object.
AudioServicesPlaySystemSound(soundID);
Try putting this pieces codes in the appropriate places and you should hear the sound.
In my Constructor:
[[AVAudioSession sharedInstance] setCategory: AVAudioSessionCategoryPlayback error: nil];
UInt32 doSetProperty = 1;
AudioSessionSetProperty (kAudioSessionProperty_OverrideCategoryMixWithOthers, sizeof(doSetProperty), &doSetProperty);
[[AVAudioSession sharedInstance] setActive: YES error: nil];
NSURL* musicFile = [NSURL fileURLWithPath:[[NSBundle mainBundle]
pathForResource:#"video-sent"
ofType:#"caf"]];
self.sentSound = [[AVAudioPlayer alloc] initWithContentsOfURL:musicFile error:nil];
[self.sentSound prepareToPlay];
The function playSentSound
- (void)playSentSound
{
DLog(#"PLay Sound %#", self.sentSound);
[self.sentSound play];
}
then later in the code i just call it
[self playSentSound];
The key here are the first 4 lines ... ;-)

Make AVFoundation not stop iPod music

Im using the AVFoundation framework to play sound files. The problem im having is that its stopping music from playing when the audio file gets used, im not saying play both files continuously, but play the sound file, then pick up the ipod music right where it left off. Is there any way i can use AVFoundation is this kind of way? or is there a better framework for it?
Here is what my code looks like:
click = [NSURL fileURLWithPath:[NSString stringWithFormat:#"#/Click.WAV", [[NSBundle mainBundle] resourcePath]]];
audioPlayer = [[AVAudioPlayer alloc]initWithContentsOfURL:click error:nil];
audioPlayer.numberOfLoops = 1;
[click release];
[audioPlayer play];
This code works completely fine, i had to type it out so ignore any problems that there might be with it.
Thanks,
Jacob
You can use the AVAudioSession class to change the audio "category" of your app: thus you can allow it to play on top of the iPod music. Use the -setCategory:error: method, and you will probably want to use AVAudioSessionCategoryAmbient. More info can be found in the Audio Session Programming Guide.

What's the SIMPLEST way to play a sound clip in an iPhone app?

I want to be able to play a sound clip in an iPhone OS app. I've seen info on both NSSound as well as AVFoundation as being means for getting sound clips played on an iPhone OS device, but I'm still not clear on the subject and could use some help. No need to spell it out for me step-by-step in actual code, but if someone could give me a hint as to the general direction (i.e. which classes I should be focusing on) in which I should start moving I'll fill in the blanks myself. So, what's the SIMPLEST way to play a sound clip in an iPhone app?
Apple has an article on this subject, see: this link
AVAudioPlayer is the simplest way to play sounds of any length, looping or not, however it requires iPhone OS 2.2 or higher. A simple example:
NSString *soundFilePath =
[[NSBundle mainBundle] pathForResource: #"sound"
ofType: #"wav"];
NSURL *fileURL = [[NSURL alloc] initFileURLWithPath: soundFilePath];
AVAudioPlayer *newPlayer =
[[AVAudioPlayer alloc] initWithContentsOfURL: fileURL
error: nil];
[fileURL release];
[newPlayer play];
[newPlayer release];
It will play virtually any file format (aiff,wav,mp3,aac) Keep in mind that you can only play one mp3/aac file at a time.
Here's the simplest way I know of:
Convert your sound file to caf (use afconvert commandline tool) and add to your project.
caf stands for Core Audio Format (I think...)
Look for SoundEffect.h and .m in Apple's sample code. I believe both Metronome and BubbleLevel have it.
Copy to your project
Write code like below:
SoundEffect *SimpleSound = [[SoundEffect alloc] initWithContentsOfFile:[mainBundle pathForResource:#"soundfile" ofType:#"caf"]];
[SimpleSound play];
[SimpleSound release];
Study SoundEffect.m to get an idea of simple sound handling.