How do I load a sound file using initWithContentsOfURL:error:? - objective-c

How do I gain access to a crashSound.wav file I've put in my Supporting Files folder of my xCode Project? Because the following code isn't working :
#interface Game()
{
// code...
AVAudioPlayer *crashSound;
// code...
}
#end
#implementation Game
- (id) init
{
// code...
NSURL *crashSoundFile = [[NSURL alloc] initWithString:#"crashSound" ]; // <--PROBLEM
crashSound = [[AVAudioPlayer alloc] initWithContentsOfURL:crashSoundFile error:NULL];
// code...
}
-(void) play // this is my "main" method that will be called once the playButton is pressed
{
[crashSound play];[crashSound play];[crashSound play];
}
#end

#"crashSound" is not a valid URL. You must supply an actual URL.
URLs to images, sounds, etc. (resources) in your project are not predictable at compile-time, and must be generated at run-time. This is easy using NSBundle.
NSBundle *bundle = [NSBundle mainBundle];
NSURL *crashSoundFile = [bundle URLForResource: #"crashSound" withExtension: #"wav"];
Ta da.

NSURL *url = [NSURL fileURLWithPath:[NSString stringWithFormat:#"%#/soundfile.extension", [[NSBundle mainBundle] resourcePath]]];

Related

pointer loop to integer conversion?

The code is suppose to make a sound either yes or yes 3 play when clicked, but I get an error before I begin to debug that says rand cannot be statically allocated, but I can't put a * there because it's an integer. I am getting a conversion error when I do that. I also tried putting a * before sound, and that solved the error issue but when the button is clicked it wont play anything. So what do I do?
#import "ViewController.h"
#import <AVFoundation/AVAudioPlayer.h>
#interface ViewController ()
#end
#implementation
- (void)viewDidLoad
{
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
}
- (void)didReceiveMemoryWarning
{
[super didReceiveMemoryWarning];
}//this is where the error breakpoint is that you show me how to make
- (IBAction)Yes {
NSInteger rand = arc4random_uniform(2);
NSString sound = rand == 0 ? #"yes" : #"yes 3";
NSURL *url = [[NSBundle mainBundle] URLForResource:sound withExtension:#"mp3"];
AVAudioPlayer* audioPlayer = [[AVAudioPlayer alloc] initWithContentsOfURL:url error:nil];
[audioPlayer play];
}
#end
I've seen this many times before, and it has to do with the fact that your audio player variable is being released before it has a chance to play the file.
You need to create a property for the audio player in your header:
#property (nonatomic, strong) AVAudioPlayer *audioPlayer;
Then in your method access that property instead of the local variable:
- (IBAction)YES {
NSInteger rand = arc4random_uniform(2);
NSString *sound = rand == 0 ? #"yes" : #"yes 3";
NSURL *url = [[NSBundle mainBundle] URLForResource:sound withExtension:#"mp3"];
self.audioPlayer = [[AVAudioPlayer alloc] initWithContentsOfURL:url error:nil];
[self.audioPlayer play];
}
Note that this has absolutely nothing to do with the sound variable you're messing with. You should be using the * to indicate a pointer when creating that variable, as shown above.

Vfr-Reader crashes on assert(range.location != NSNotFound);

I am using thisopen source control called Vfr Reader to show pdf files in my app. All was working on iOS 7. After iOS update app crashes when I try on open a pdf file.
I am using this code to initialize pdf reader.
NSString *fileName = [[NSBundle mainBundle] pathForResource:#"PdfName" ofType:#"pdf"];
ReaderDocument *document = [ReaderDocument withDocumentFilePath:fileName password:nil];
if (document != nil)
{
ReaderViewController *readerViewController = [[ReaderViewController alloc] initWithReaderDocument:document];
readerViewController.delegate = self;
readerViewController.modalTransitionStyle = UIModalTransitionStyleCrossDissolve;
readerViewController.modalPresentationStyle = UIModalPresentationFullScreen;
[self presentViewController:readerViewController animated:YES completion:Nil];
}
App crashes in this fuction of vfr
+ (NSString *)relativeFilePath:(NSString *)fullFilePath
{
assert(fullFilePath != nil); // Ensure that the full file path is not nil
NSString *applicationPath = [ReaderDocument applicationPath]; // Get the application path
NSRange range = [fullFilePath rangeOfString:applicationPath]; // Look for the application path
assert(range.location != NSNotFound); // **Crashes here**
return [fullFilePath stringByReplacingCharactersInRange:range withString:#""]; // Strip it out
}
On crash debugger shows these values.
fullFilePath = #"/Users/GuruTraxiOSDev01/Library/Developer/CoreSimulator/Devices/CC9412A6-9A95-4F46-89BA-8ECC13D0AF19/data/Containers/Bundle/Application/D2DC440B-F010-4575-93FD-3CB05BFF4F78/AppName.app/PdfName.pdf" 0x798c9b30
range = location=2147483647, length=0
applicationPath =#"/Users/GuruTraxiOSDev01/Library/Developer/CoreSimulator/Devices/CC9412A6-9A95-4F46-89BA-8ECC13D0AF19/data/Containers/Data/Application/32D612DE-FFD2-4C1E-B403-CDA177B460A6" 0x798b46b0
I already confirmed the file's existence.
Can anyone help please!
EDIT: This question solved crash on file load. But app still crashes on
CGContextDrawPDFPage(context, thePDFPageRef);
I was facing the same issue, so I made some changes to the Library Files which should not be an option as such but in this case I didn't have any choice to get it to work. So to make your code work follow the instruction below:
Go to ReaderDocument.m file and make the following changes:
+ (NSString *)documentsPath
{
//Make changes to return the NSBundle path.
NSString *bundlePath = [[NSBundle mainBundle] bundlePath];
NSFileManager *fileManager = [NSFileManager new]; // File manager instance
NSURL *pathURL = [fileManager URLForDirectory:NSDocumentDirectory inDomain:NSUserDomainMask appropriateForURL:nil create:YES error:NULL];
// return [pathURL path]; // Path to the application's "~/Documents" directory // Code changes.
return bundlePath;
}
If you had a breakpoint just delete it, that solve it for me.
Breakpoint navigator => select the breakpoint then delete

Value from userDefaults not populating URL query string

I am making this chat app with works with a .php file on my webserver to store the data in a SQL db
Here is my code so far:
#import "vtchatViewController.h"
#interface vtchatViewController ()
#end
#implementation vtchatViewController
#synthesize messageBox, messageView, Send, Refresh;
- (void)viewDidLoad
{
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
NSString *usrName = [[NSUserDefaults standardUserDefaults] stringForKey:#"user_name"];
NSURL *url = [NSURL URLWithString:#"http://server.com/ios/messages.php"]; [messageView loadRequest:[NSURLRequest requestWithURL:url]];
}
- (IBAction)refreshButton:(id)sender {
NSURL *url = [NSURL URLWithString:#"http://server.com/ios/messages.php"]; [messageView loadRequest:[NSURLRequest requestWithURL:url]];
}
- (IBAction)sendButton:(id)sender {
// server.com/ios/add.php?user=Username here&message=Message Her
[messageBox resignFirstResponder];
NSString* urlString = [[NSString stringWithFormat:#"http://server.com/ios/add.php?user=",usrName "&message=%#", messageBox.text] stringByAddingPercentEscapesUsingEncoding : NSUTF8StringEncoding];
NSURL *add = [NSURL URLWithString:urlString];
[messageView loadRequest:[NSURLRequest requestWithURL:add]];
messageBox.Text = #"";
}
- (void)didReceiveMemoryWarning
{
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
#end
However on the line "viewDidLoad" I can't get it to use the username from my settings bundle:
NSString* urlString = [[NSString stringWithFormat:#"http://server.com/ios/add.php?user=",usrName "&message=%#", messageBox.text] stringByAddingPercentEscapesUsingEncoding : NSUTF8StringEncoding];
NSURL *add = [NSURL URLWithString:urlString];
I get the error "Use of undeclared indentifier 'usrName' and also I have no idea if I did implent the "usrName" correct for use in this
I simply need it to send data to "server.com/ios/add.php?" where data should be in this format: "user=Username here&message=Message here"
I got it working if I just use a fixed username, but as said, I have no idea how to make the thing use the username stored in my settings file
Thanks in advance
You need to use string format tokens to get it to insert the username into the urlString variable like this:
NSString* urlString = [[NSString stringWithFormat:#"http://server.com/ios/add.php?user=%#&message=%#", usrName, messageBox.text];
That should help you understand why your format string wasn't working and why you were getting that error. My code above isn't escaping the values of usrName or messageBox.text so you'll need to add those back into your code.
you should let you usrName beacome like a interface variable.
like that:
#interface vtchatViewController () {
NSString *usrName;
}
#end
#implementation vtchatViewController
- (void)viewDidLoad
{
...
NSString *usrName = [[NSUserDefaults standardUserDefaults] stringForKey:#"user_name"];
...
}
#end

IOS can I use AVAudioPlayer on the appDelegate?

I have a TabBarController with two tabs and I want to play music on both tabs. Right now I have my code on the main appDelegate
NSURL *url = [NSURL fileURLWithPath:[[NSBundle mainBundle]
pathForResource:#"My Song"
ofType:#"m4a"]]; // My Song.m4a
NSError *error;
self.audioPlayer = [[AVAudioPlayer alloc]
initWithContentsOfURL:url
error:&error];
if (error)
{
NSLog(#"Error in audioPlayer: %#",
[error localizedDescription]);
} else {
//audioPlayer.delegate = self;
[audioPlayer prepareToPlay];
}
but I'm getting the error Program received signal: "SIGABRT" on UIApplicationMain
Is there a better way to accomplish what I'm trying to do? If this is how I should do it, where do I start checking for problems?
yes you can use AVAudioPlayer in App Delegate.
What you need to do is:-
In appDelegate.h file do:-
#import <AVFoundation/AVFoundation.h>
#import <AudioToolbox/AudioToolbox.h>
AVAudioPlayer *_backgroundMusicPlayer;
BOOL _backgroundMusicPlaying;
BOOL _backgroundMusicInterrupted;
UInt32 _otherMusicIsPlaying;
Make backgroundMusicPlayer property and sythesize it.
In appDelegate.m file do:-
Add these lines in did FinishLaunching method
NSError *setCategoryError = nil;
[[AVAudioSession sharedInstance] setCategory:AVAudioSessionCategoryAmbient error:&setCategoryError];
// Create audio player with background music
NSString *backgroundMusicPath = [[NSBundle mainBundle] pathForResource:#"SplashScreen" ofType:#"wav"];
NSURL *backgroundMusicURL = [NSURL fileURLWithPath:backgroundMusicPath];
NSError *error;
_backgroundMusicPlayer = [[AVAudioPlayer alloc] initWithContentsOfURL:backgroundMusicURL error:&error];
[_backgroundMusicPlayer setDelegate:self]; // We need this so we can restart after interruptions
[_backgroundMusicPlayer setNumberOfLoops:-1]; // Negative number means loop forever
Now implement delegate methods
#pragma mark -
#pragma mark AVAudioPlayer delegate methods
- (void) audioPlayerBeginInterruption: (AVAudioPlayer *) player {
_backgroundMusicInterrupted = YES;
_backgroundMusicPlaying = NO;
}
- (void) audioPlayerEndInterruption: (AVAudioPlayer *) player {
if (_backgroundMusicInterrupted) {
[self tryPlayMusic];
_backgroundMusicInterrupted = NO;
}
}
- (void)tryPlayMusic {
// Check to see if iPod music is already playing
UInt32 propertySize = sizeof(_otherMusicIsPlaying);
AudioSessionGetProperty(kAudioSessionProperty_OtherAudioIsPlaying, &propertySize, &_otherMusicIsPlaying);
// Play the music if no other music is playing and we aren't playing already
if (_otherMusicIsPlaying != 1 && !_backgroundMusicPlaying) {
[_backgroundMusicPlayer prepareToPlay];
if (soundsEnabled==YES) {
[_backgroundMusicPlayer play];
_backgroundMusicPlaying = YES;
}
}
}

How to call a method defined in another class

I have a class named as Backgroundmusic.h file is
#import "UIKit/UIKit.h"
#import "AVFoundation/AVFoundation.h"
#import "AudioToolbox/AudioToolbox.h"
#interface Backgroundmusic : NSObject{
}
-(void)playBgmusic:(BOOL) issoundon;
#end
Backgroundmusic.m is
-(void)playBgmusic:(BOOL)issoundon {
//AVAudioPlayer *myExampleSound; //this variable can be named differently
if ( issoundon==TRUE) {
NSString *path =[[NSBundle mainBundle] pathForResource:"bg" ofType:#"wav"];
SystemSoundID soundID;
AudioServicesCreateSystemSoundID((CFURLRef) [NSURL fileURLWithPath:path]
,&soundID);
AudioServicesPlaySystemSound(soundID);
}
else {
NSString *path =[[NSBundle mainBundle] pathForResource:nil ofType:#"wav"];
SystemSoundID soundID;
AudioServicesCreateSystemSoundID((CFURLRef) [NSURL fileURLWithPath:path]
,&soundID);
AudioServicesPlaySystemSound(soundID);
}
}
Basically what i am trying to do is setting a background music to my app at the time of beginning and allow the user to stop it in the middle
so in my xAppdelegate.m i have called this function as
- (void)applicationDidFinishLaunching:(UIApplication *)application {
Backgroundmusic *bgm=[[Backgroundmusic alloc] init];
[bgm playBgmusic:TRUE];
}
but at this time my app terminates can someone tell me whats the issue here???
what the error message you are getting ? When application terminate you can check that in gdb window. It will show the proper error message. Post that error message in this thread.