Can I add sounds to Xcode's Storyboard mode? - xcode

I'm new to creating apps for iOS and I'm using storyboard mode. I wanted to know how can I add sounds. Also, does it require coding?

You can use this for playback of simple sounds. It uses the AVFoundation framework, which will require you to add AVFoundation to your project, and use #import <AVFoundation/AVFoundation.h>
- (IBAction) myPlayAction {
AVAudioPlayer *data;
NSString *name = [[NSString alloc] initWithFormat:#"SoundName"];
NSString *source = [[NSBundle mainBundle] pathForResource:name ofType:#"mp3"];
if (data) {
[data stop];
data = nil;
}
data=[[AVAudioPlayer alloc] initWithContentsOfURL:[NSURL fileURLWithPath: source] error:NULL];
data.delegate = self;
[data prepareToPlay];
[data play];
}

Related

no visible #interface for 'UIImagePickerController

So my code says
no visible #interface for UIImagePicker Controller
I am using a Tab View Controller
My code for my FirstViewController.m is
#import "FirstViewController.h"
#interface FirstViewController () <UIImagePickerControllerDelegate, UINavigationControllerDelegate> {
UIImagePickerController *bailey;
UIImagePickerController *baileys;
UIImage *image;
IBOutlet UIImageView *imageView;
}
- (IBAction)takePhoto;
- (IBAction)chooseExisting;
#end
#implementation FirstViewController
- (IBAction)takePhoto {
bailey = [[UIImagePickerController alloc]init];
bailey.delegate = self;
[bailey setSourceType:UIImagePickerControllerSourceTypeCamera];
[self presentViewController:bailey animated:YES completion:NULL];
}
- (IBAction)chooseExisting {
baileys = [[UIImagePickerController alloc] init];
baileys.delegate = self;
[baileys setSourceType:UIImagePickerControllerSourceTypePhotoLibrary];
[self presentViewController:baileys animated:YES completion:NULL];
}
- (void) imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info {
image = [info objectForKey:UIImagePickerControllerOriginalImage];
[imageView setImage:image];
[self dismissViewControllerAnimated:YES completion:NULL];
}
- (void) imagePickerControllerDidCancel:(UIImagePickerController *)bailey {
[self dismissViewControllerAnimated:YES completion:NULL];
}
- (IBAction)ShareFB {
if ([SLComposeViewController isAvailableForServiceType:SLServiceTypeFacebook]) {
slComposeViewController = [SLComposeViewController composeViewControllerForServiceType:SLServiceTypeFacebook];
[slComposeViewController addImage:[UIImage imageNamed:#"image"]];
[slComposeViewController addURL:[NSURL URLWithString:#"http://www.agfg.com.au"]];
[self presentViewController:slComposeViewController animated:YES completion:NULL];
//I borrowed these lines of code from http://www.bit.ly/174eqjy
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *appFile = [documentsDirectory stringByAppendingString:#"upload.png"];
NSString *upLoad = [documentsDirectory stringByAppendingString:#"upload.png"];
NSData *myData = [[NSData alloc]initWithContentsOfFile:appFile];
//Here is the line that fails
[bailey addAttachmentData:myData mimeType:#"image/png" fileName:#"upload"];
//Up to here are the borrowed code lines.
}
else {
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:#"No Facebook Account Detected" message:#"There are no Facebook Accounts Detected. You can configure them in Settings." delegate:nil cancelButtonTitle:#"Dismiss" otherButtonTitles:nil];
[alert show];
}}
- (void)viewDidLoad
{
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
}
- (void)didReceiveMemoryWarning
{
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
#end
And my code for my FirstViewController.h is
#import <UIKit/UIKit.h>
#import <Social/Social.h>
#interface FirstViewController : UIViewController {SLComposeViewController *slComposeViewController;
UIImage *upLoad;}
- (IBAction)ShareFB;
#end
My app is designed to Take a photo and display the photo (and it does that) and then save that image to the local documents folder on the app (which I got from another post) and then specify that image to upload to Facebook (which I have)
All that works except the saving to a local documents.
If you need to store file in documents directory, use like this,
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0]; // Get documents folder
NSString *dataPath = [documentsDirectory stringByAppendingPathComponent:#"Images"];
if (![[NSFileManager defaultManager] fileExistsAtPath:dataPath])
{
[[NSFileManager defaultManager] createDirectoryAtPath:dataPath withIntermediateDirectories:NO attributes:nil error:nil];
}
NSString *imageFilePath = [NSString stringWithFormat:#"%#/%#",dataPath,#"upload.png"];
UIImage *image = [UIImage imageNamed:#"image"]; //Here place your image
NSData *imageData = [NSData dataWithData:UIImagePNGRepresentation(image)];
[imageData writeToFile:imageFilePath atomically:YES];
If you need to attach image in facebook, use this statement,
[slComposeViewController
addAttachmentData:UIImagePNGRepresentation(image, 1) mimeType:#"image/png" fileName:#"upload.png"];
With the help of Karthika, and his facebook upload code, I was typing it in when I realised that I did not need to implement local documents saving.
Facebook let me add the image in without saving it.
Thanks though Karthika, I could not have done it without you.

xcode cannot get sound file to play with AVAudioPlayer

I am new to iOS and trying to add sound to my app. I have followed several tutorials about adding a simple sound file to my project, but ALL with the same result. I get no errors, but no sound plays. Any ideas on what I am doing wrong? Any help would be appreciated!
- (IBAction)playSound:(id)sender {
NSString *soundFilePath = [[NSBundle mainBundle] pathForResource:#"test" ofType:#"mp3"];
NSURL *soundFileURL = [NSURL fileURLWithPath:soundFilePath];
NSLog(soundFilePath);
NSError *error;
AVAudioPlayer *player = [[AVAudioPlayer alloc] initWithContentsOfURL:soundFileURL error:&error];
player.numberOfLoops = 1;
[player play];
}
**UPDATE***
So I never had any luck with the above code which is very discouraging, but I did end up getting it to work using the AudioToolbox Framework instead, using this:
SystemSoundID soundID;
NSString *soundFile = [[NSBundle mainBundle]
pathForResource:#"test" ofType:#"mp3"];
AudioServicesCreateSystemSoundID((__bridge CFURLRef)
[NSURL fileURLWithPath:soundFile], & soundID);
AudioServicesPlaySystemSound(soundID);
Can anyone explain to me the difference, why this one works and the other does not?? I am curious more than anything. Would love some clarification.
Finally figured it out. I needed to create a property for AVAudioPlayer in my header file in order to get it to work. Here is what I did:
// .h file
#interface ThirdViewController : UIViewController {
AVAudioPlayer *audioPlayer;
}
#property (nonatomic, retain) AVAudioPlayer *audioPlayer;
- (void) playSound //method in .m file
{
NSURL *url = [NSURL fileURLWithPath:[[NSBundle mainBundle]
pathForResource:#"test"
ofType:#"mp3"]];
NSError *error;
audioPlayer = [[AVAudioPlayer alloc] initWithContentsOfURL:url error:&error];
[audioPlayer play];
}
Simplify your code by doing the follow. Also drop your test.mp3 to the root of your project directory in xcode. Your mp3 placement and location is very important. Also ensure volume is up, and vibrate is off of your device, and it's unmuted.
NSURL *url = [NSURL fileURLWithPath:[[NSBundle mainBundle]
pathForResource:#"test"
ofType:#"mp3"]];
AVAudioPlayer *audioPlayer = [[AVAudioPlayer alloc]
initWithContentsOfURL:url
error:nil];
[audioPlayer play];
Make sure you install quartz.h, or a specific framework that supports audio players. Just double check.
Had the same problem a while back and the framework must be installed properly.

Merging RTF Files With Cocoa

How would one do this? I know just merging NSData doesn't work.
Playing with NSAttributedString should work, something like the code shown below
This is a very quick and dirty way to merge many RTF files together
- (void)mergeRTF:(NSURL*)rtf1 :(NSURL*)rtf2 :(NSURL*)merged {
NSMutableDictionary *options = [NSMutableDictionary dictionary];
[options setObject:[NSNumber numberWithUnsignedInteger:NSUTF8StringEncoding]
forKey:NSCharacterEncodingDocumentOption];
NSDictionary *docAttrs = nil;
NSError* error = nil;
NSAttributedString *rtfText1 = [[NSAttributedString alloc] initWithURL:rtf1
options:options
documentAttributes:&docAttrs
error:&error];
NSAttributedString *rtfText2 = [[NSAttributedString alloc] initWithURL:rtf2
options:options
documentAttributes:&docAttrs
error:&error];
NSMutableAttributedString* whole = [[NSMutableAttributedString alloc] initWithAttributedString:rtfText1];
[whole appendAttributedString:rtfText2];
NSData* data = [whole RTFFromRange:NSMakeRange(0, whole.length) documentAttributes:nil];
[data writeToURL:merged atomically:YES];
}

Force plaintext copy from a Cocoa WebView

I have a Cocoa Webview subclass, and I need to make all text copied from it be plaintext only. I have tried overriding -copy and -pasteboardTypesForSelection, but no luck, and debugging code seems to indicate that those methods are never called. I've also tried setting -webkit-user-modify to read-write-plaintext-only in the css (this would also work in this situation) but that seemed to have no effect.
Any ideas?
Okay this seems to work (with the subclass instance as its own editing delegate):
- (BOOL)webView:(WebView *)webView doCommandBySelector:(SEL)command
{
if (command == #selector(copy:)) {
NSString *markup = [[self selectedDOMRange] markupString];
NSData *data = [markup dataUsingEncoding: NSUTF8StringEncoding];
NSNumber *n = [NSNumber numberWithUnsignedInteger: NSUTF8StringEncoding];
NSDictionary *options = [NSDictionary dictionaryWithObject:n forKey: NSCharacterEncodingDocumentOption];
NSAttributedString *as = [[NSAttributedString alloc] initWithHTML:data options:options documentAttributes: NULL];
NSString *selectedString = [as string];
[as autorelease];
NSPasteboard *pasteboard = [NSPasteboard generalPasteboard];
[pasteboard clearContents];
NSArray *objectsToCopy = [NSArray arrayWithObject: selectedString];
[pasteboard writeObjects:objectsToCopy];
return YES;
}
return NO;
}
Not sure if this is the best way.

Can't use two "audioPlayerDidFinishPlaying"

Can you please tell me how to fix this? I want to release two different AVAudioPlayer when they finish playing, but separately.
Here's my code:
.h File
#interface ViewController : UIViewController <AVAudioPlayerDelegate>
{
NSString *path;
}
- (IBAction)Short:(id)sender;
- (IBAction)BeatLong:(id)sender;
.m File
AVAudioPlayer *media;
AVAudioPlayer *media2;
- (IBAction)Short:(id)sender
{
path = [[NSBundle mainBundle] pathForResource:#"Short" ofType:#"wav"];
media = [[AVAudioPlayer alloc] initWithContentsOfURL:[NSURL fileURLWithPath:path] error:NULL];
[media setDelegate:self];
[media play];
}
- (IBAction)Beat:(id)sender
{
path = [[NSBundle mainBundle] pathForResource:#"Beat" ofType:#"mp3"];
media2 = [[AVAudioPlayer alloc] initWithContentsOfURL:[NSURL fileURLWithPath:path] error:NULL];
[media2 setDelegate:self];
[media2 play];
}
(Open the image in a new tab to see it better ^^,)
Nay, that's illegal on the grounds of the language.
You have to distinguish the different players according to the AVAudioPlayer * pointer
submitted with the message.
If you just want to release it, just write
- (void) audioPlayerDidFinishPlaying:(AVAudioPlayer *)aPlayer successfully:(BOOL)flag
{
[aPlayer release];
}
and you're done and illegal too, since you don't own aPlayer.
But a better solution would be to detect which audio player you own and release it.
- (void) audioPlayerDidFinishPlaying:(AVAudioPlayer *)aPlayer successfully:(BOOL)flag
{
if ( aPlayer == self.media )
[self.media release];
else if ( aPlayer == self.media2 )
[self.media2 release];
// other players cannot be released, since we don't know anything about their owner.
}

Resources