How do i play many sounds selected by picker? - objective-c

I want to make an app playing sound selected by picker.
When i select a file by picker, if i touch button, the sound will play.
But, it cannot.
I cannot point the miss of the code.
Anyone can help me to troubleshoot my code?
Here is my code for troubleshooting.
.H file
#import <UIKit/UIKit.h>
#import <AVFoundation/AVFoundation.h>
#interface ViewController : UIViewController <
UIPickerViewDelegate,UIPickerViewDataSource,AVAudioPlayerDelegate> {
NSArray *ap;
NSString *si;
UIButton * utab;
AVAudioPlayer *apr;
}
#property (weak, nonatomic) IBOutlet UILabel *ll;
#property (weak, nonatomic) IBOutlet UIImageView *igv;
#property (weak, nonatomic) IBOutlet UIPickerView *pv;
#property (weak, nonatomic) NSArray *msa;
#end
.M file
#import "ViewController.h"
#import <AVFoundation/AVFoundation.h>
#interface ViewController ()
#property AVAudioPlayer *apr;
#end
#implementation ViewController
#synthesize ll,igv,pv;
- (void)viewDidLoad
{
[pv setDelegate:self];
[pv setDataSource:self];
[ll setText:[ap objectAtIndex:0]];
ap = [NSArray arrayWithObjects:#"AAA",#"BBB",#"CCC",#"DDD",#"EEE", nil];
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
NSURL *url = [NSURL fileURLWithPath:[NSString stringWithFormat:#"%#.m4a",[[NSBundle mainBundle] resourcePath]]];
NSError *error;
self.apr = [[AVAudioPlayer alloc] initWithContentsOfURL:url error:&error];
apr.numberOfLoops = 2;
}
-(NSInteger)numberOfComponentsInPickerView:(UIPickerView *)pickerView {
return 1;
}
-(NSInteger)pickerView:(UIPickerView *)pickerView numberOfRowsInComponent:(NSInteger)component {
return [ap count];
}
-(NSString *)pickerView:(UIPickerView *)pickerView titleForRow:(NSInteger)row forComponent: (NSInteger)component {
return [ap objectAtIndex:row];
}
-(void)pickerView:(UIPickerView *)pickerView didSelectRow:(NSInteger)row inComponent: (NSInteger)component {
si = [ap objectAtIndex:row];
[ll setText:si];
NSString *in = [NSString stringWithFormat:#"%#.jpg",si];
UIImage *tig = [UIImage imageNamed:in ];
[igv setImage:tig];
}
- (IBAction)utabu {
[self.apr play];
}
#end

Most likely the sound file could not be loaded. You should check the error variable after initializing the AVAudioPlayer.
The code for creating the URL objects is also wrong. You should use:
[[NSBundle mainBundle] URLForRessource:<filename> withExtension:"m4a"]
Also you would have to create a new AudioPlayer each time a sound file is selected.
Next time please use better variable names and not just two or three letter garbage.

Related

How can i make a random sound array with objective c?

So i've done the tutorial where you code a button so that when you press it a sound plays. I'm trying to modify it so that when the button is pressed, a random sound plays.
here is the code:
viewcontroller.h
#import <UIKit/UIKit.h>
#import <AudioToolbox/AudioToolbox.h>
#interface STViewController : UIViewController
- (IBAction)playAudio:(id)sender;
#property (nonatomic, strong) NSArray *sounds;
#end
viewcontroller.m
#import <AVFoundation/AVFoundation.h>
#import "STViewController.h"
#interface STViewController ()
#property (weak, nonatomic) IBOutlet UIButton *playAudio;
#end
#implementation STViewController
- (IBAction)playAudio:(id)sender {
AVAudioPlayer *audioPlayer;
NSString *audioPath = [[NSBundle mainBundle] pathForResource:#"Woof" ofType:#"mp3"];
NSURL *audioURL = [NSURL fileURLWithPath:audioPath];
NSError *audioError = [[NSError alloc] init];
audioPlayer = [[AVAudioPlayer alloc] initWithContentsOfURL:audioURL error:&audioError];
if (!audioError) {
[audioPlayer play];
NSLog(#"Woof!");
}
else {
NSLog(#"Error!");
}
}
- (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
I've been dabbling with something along these lines
- (NSArray *)sounds
{
NSArray *sounds = [NSArray arrayWithObjects:
#"Woof.mp3",
#"Meow.mp3",
#"tweet.mp3",
#"Squeak.mp3",
#"Moo.mp3",
#"Croak.mp3",
#"Toot.mp3",
#"Quack.mp3",
#"Blub.mp3",
#"OWOwOw.mp3",
#"Fox.mp3",
nil];
return sounds;
}
but i'm not really sure how to make it random or even implement in in the code that I have going right now. Anyone have any ideas?
Just make it random try below:-
NSMutableArray *array=[NSMutableArray
arrayWithObjects:
#"Woof.mp3",
#"Meow.mp3",
#"tweet.mp3",
#"Squeak.mp3",
#"Moo.mp3",
#"Croak.mp3",
#"Toot.mp3",
#"Quack.mp3",
#"Blub.mp3",
#"OWOwOw.mp3",
#"Fox.mp3",
nil];
// now use exchangeobject with index api
int i=0;
for(i=0;i<=[array count]; i++)
{
NSInteger rand=(arc4random() %10);
[array exchangeObjectAtIndex:i
withObjectAtIndex:rand];
}

PickerView in Objective-C

After I enter the following link, the device just display the black screen. Could anyone can please answer what is the problem? Actually, I am wondering the problem is occurring in this part:
-(void)pickerView:(UIPickerView *)pickerView didSelectRow:(NSInteger)row
inComponent:(NSInteger)component{
picCode = [cameraCode objectAtIndex:row];
}
Source Code:
//testingProgram.h
#import <UIKit/UIKit.h>
#interface testingProgramViewController : UIViewController
<UIPickerViewDelegate, UIPickerViewDataSource>
{
NSTimer *aTimer;
NSString *picCode;
UIPickerView *regionPicker;
NSArray *regionNames;
NSArray *cameraCode;
UILabel *testingLabel;
UITextField *regionTextField;
}
#property (nonatomic, retain) IBOutlet UIPickerView *regionPicker;
#property (nonatomic, retain) IBOutlet UILabel *testingLabel;
#property (nonatomic, retain) IBOutlet UITextField *regionTextField;
#property (nonatomic, retain) NSArray *regionNames;
#property (nonatomic, retain) NSArray* cameraCode;
-(IBAction)textFieldReturn:(id)sender;
#end
//testingProgram.m
#import "testingProgramViewController.h"
#interface testingProgramViewController ()
#property (weak, nonatomic) IBOutlet UIImageView *testingPic;
#end
#implementation testingProgramViewController
#synthesize regionPicker, regionNames, cameraCode;
#synthesize testingLabel, regionTextField;
#pragma mark -
#pragma mark PickerView DataSource
- (NSInteger)numberOfComponentsInPickerView:(UIPickerView *)pickerView {
return 1;
}
- (NSInteger)pickerView:(UIPickerView *)pickerView numberOfRowsInComponent:(NSInteger)component {
return [regionNames count];
}
- (NSString *)pickerView:(UIPickerView *)pickerView
titleForRow:(NSInteger)row
forComponent:(NSInteger)component {
return [regionNames objectAtIndex:row];
}
#pragma mark -
#pragma mark PickerView Delegate
-(void)pickerView:(UIPickerView *)pickerView didSelectRow:(NSInteger)row
inComponent:(NSInteger)component{
picCode = [cameraCode objectAtIndex:row];
}
- (void) obtainPic:(NSString *)picName{
NSString *urlLink = [[NSString alloc] initWithFormat:#"http://tdcctv.data.one.gov.hk/%#.JPG", picName];
NSURL *url = [NSURL URLWithString:urlLink];
UIImage *image = [UIImage imageWithData: [NSData dataWithContentsOfURL:url]];
self.testingPic.image = image;
}
-(IBAction)textFieldReturn:(id)sender {
[sender resignFirstResponder];
}
-(void)timerFired:(NSTimer *) theTimer {
[self obtainPic:picCode];
}
- (void)viewDidLoad {
[super viewDidLoad];
self.regionNames = [[NSArray alloc] initWithObjects:
#"Hong Kong Island", #"Kowloon", #"Tsuen Wan",
#"Tuen Mun & Tin Shui Wai", #"Tai Po, North and Yuen Long", #"Shatin & Ma On Shan", #"Lantau", nil];
self.cameraCode = [[NSArray alloc] initWithObjects: #"H429F", #"K202F", #"TW117F", #"TI101F", #"BC702F", #"ST115F", #"TC551F", nil],
picCode = #"H422F2";
[self obtainPic:picCode];
aTimer = [NSTimer scheduledTimerWithTimeInterval:60.0
target:self
selector:#selector(timerFired:)
userInfo:nil
repeats:YES];
}
#end

UITableView push to My webView

I'd like to start by apologising as I'm sure this question has been answered, in various forms on this site and others, but I just can't seem to implement any similar threads
It's just I have been trying to push a array of search engines into my webView,
I have populated the table with a .plist or NSMutableArray and I have an array of both kinds with Url's in I have manages to load a subview but I an really struggling to get my web view loading.
I think I'm ok until didSelectRowAtIndexPath and the webView load request. Ok thinking about it I have only populated the table and put IBOUTLET (nonatomic, retain) UIWebView *webView and synthesised it in my WebViewController.
And as Background my TableViewController is embedded in a NavigationController and a WebView in a UIViewController
If anyone is willing to help me out I'm more than willing to donate as this has caused way too many sleepless nights.
Here is a link to my project if it would help anyone http://dl.dropbox.com/u/28335617/TableViewArrays.zip
Thank you very much for any help offered
Here is my TableViewController.h
#class WebViewController;
#import <UIKit/UIKit.h>
#interface TableViewController : UITableViewController <UITableViewDataSource, UITableViewDelegate> {
WebViewController *viewController;
IBOutlet UITableView *mytableView;
}
#property (strong, nonatomic) IBOutlet UITableView *mytableView;
#property (nonatomic, retain) WebViewController *viewController;
#property (nonatomic, retain) NSMutableArray *searchData, *tableData, *tableUrl;
#end
Here is my TableViewController.m
#import "TableViewController.h"
#import "TableAppDelegate.h"
#import "WebViewController.h"
#interface TableViewController ()
#end
#implementation TableViewController
#synthesize mytableView;
#synthesize viewController;
#synthesize searchData, tableData, tableUrl;
NSMutableArray *searchData, *tableData, *tableUrl;
- (void)viewDidLoad
{
[super viewDidLoad];
tableUrl = [[NSMutableArray alloc] init];
[tableUrl addObject: #"http://www.google.com"];
[tableUrl addObject: #"http://www.bing.com"];
[tableUrl addObject: #"http://www.dogpile.com"];
[tableUrl addObject: #"http://www.wikipedia.com"];
[tableUrl addObject: #"http://www.ask.com"];
[tableUrl addObject: #"http://www.yahoo.com"];
[tableUrl addObject: #"http://www.aol.com"];
[tableUrl addObject: #"http://www.altavista.com"];
[tableUrl addObject: #"http://www.gigablast.com"];
[tableUrl addObject: #"http://www.msn.com"];
[tableUrl addObject: #"http://www.mamma.com"];
self.title = #"Search Engines";
//ARRAY FOR PLIST
// Find out the path of recipes.plist
NSString *path = [[NSBundle mainBundle] pathForResource:#"searchData" ofType:#"plist"];
searchData = [[NSMutableArray alloc] initWithContentsOfFile:path];
// Load the file content and read the data into arrays
NSDictionary *dict = [[NSDictionary alloc] initWithContentsOfFile:path];
tableData = [dict objectForKey:#"SearchEngines"];
// tableUrl = [dict objectForKey:#"SearchAddress"];
// NSString *path = [[NSBundle mainBundle] pathForResource:#"sEArray" ofType:#"plist"];
// sEArray = [[NSMutableArray alloc] initWithContentsOfFile:path];
// NSString *urlArray = [[NSBundle mainBundle] pathForResource:#"urlsArray" ofType:#"plist"];
//urlsArray = [[NSMutableArray alloc] initWithContentsOfFile:urlArray];
}
- (void)didReceiveMemoryWarning
{
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
#pragma mark - Table view data source
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
// Return the number of sections.
return 1;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection: (NSInteger)section
{
// Return the number of rows in the section.
return [self.tableData count];
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath: (NSIndexPath *)indexPath
{
static NSString *CellIdentifier = #"Cell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier forIndexPath:indexPath];
if (cell == nil) {
}
// Configure the cell...
NSInteger row = [indexPath row];
cell.textLabel.text = [tableData objectAtIndex:row];
cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
return cell;
}
#pragma mark - Table view delegate
-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
}
#end
And here is my WebViewController.h
#import <UIKit/UIKit.h>
#interface WebViewController : UIViewController {
NSMutableArray *tableURL;
}
#property (nonatomic, retain) IBOutlet UIWebView *webView;
#property (nonatomic, retain) NSMutableArray *tableUrl;
#end
And WebViewController.m
#import "TableAppDelegate.h"
#import "TableViewController.h"
#import "WebViewController.h"
#interface WebViewController ()
#end
#implementation WebViewController
#synthesize tableUrl;
#synthesize webView;
Not tested. Add SequgeIdentifier "WebView" in IB
in tableviewcontroller add:
- (void)viewDidLoad
{
...
tableUrl = [dict objectForKey:#"SearchAddress"];
}
-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
[self performSegueWithIdentifier:#"WebView" sender:self];
}
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
if ([[segue identifier] isEqualToString:#"WebView"])
{
WebViewController *webViewController = segue.destinationViewController;
NSIndexPath *selectedPath = [self.tableView indexPathForSelectedRow];
webViewController.tableUrl = [tableUrl objectAtIndex:[selectedPath row]];
[self.tableView deselectRowAtIndexPath:selectedPath animated:YES];
}
}
in webviewcontroller
#interface WebViewController : UIViewController {
NSString *tableURL;
}
#property (nonatomic, retain) IBOutlet UIWebView *webView;
#property (nonatomic, retain) NSString *tableUrl;
#end
- (void)viewDidLoad
{
[super viewDidLoad];
// Do any additional setup after loading the view.
//Create a URL object.
NSURL *url = [NSURL URLWithString:tableUrl];
//URL Requst Object
NSURLRequest *requestObj = [NSURLRequest requestWithURL:url];
//Load the request in the UIWebView.
[webView loadRequest:requestObj];
}
What exactly is not working?
Looking at your code, I immediately see that you cell initiation code is empty
if (cell == nil) {
}
I think you should initiate your cell with something like this:
cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier] autorelease];

AudioPlayer not playing on a second view controller

I have a sound playing on buttons pushed from the main view controller which works fine. On the next view controller I also want a sound to play on buttons pushed but I'm not getting any sound. I set the two .h and .m files the same. What could my problem be? Thank you for any help.
my .m file:
#import "AboutView.h"
#import <AVFoundation/AVFoundation.h>
#import <CoreAudio/CoreAudioTypes.h>
#interface AboutView ()
#end
#implementation AboutView
#synthesize support;
#synthesize facebook;
#synthesize kmbdev;
#synthesize back;
#synthesize player2;
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNi{
if (self) {
// Custom initialization
}
return self;
self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
NSString *soundFilePath = [[NSBundle mainBundle] pathForResource: #"sound1" ofType: #"wav"];
NSURL *fileURL = [[NSURL alloc] initFileURLWithPath: soundFilePath];
self.player2 = [[AVAudioPlayer alloc] initWithContentsOfURL: fileURL error: NULL];
player2.volume = .5;
[player2 prepareToPlay];
}
My .h file:
#import "ViewController.h"
#import <MessageUI/MessageUI.h>
#import <AVFoundation/AVFoundation.h>
#import <CoreAudio/CoreAudioTypes.h>
#class ViewController;
#interface AboutView : UIViewController <MFMailComposeViewControllerDelegate, AVAudioPlayerDelegate>{
AVAudioPlayer *player2;
}
#property (strong, nonatomic) IBOutlet UIButton *back;
- (IBAction)back:(id)sender;
#property (strong, nonatomic) IBOutlet UIButton *support;
#property (strong, nonatomic) IBOutlet UIButton *facebook;
#property (strong, nonatomic) IBOutlet UIButton *kmbdev;
- (IBAction)email:(id)sender;
#property (strong, nonatomic) AVAudioPlayer *player2;
#end
I have [player2 play]; at my prepare for segue and IBaction as I do on the main view controller.
Add this code in ViewDidLoad method of 2nd controller:
NSString *soundFilePath = [[NSBundle mainBundle] pathForResource: #"sound1" ofType: #"wav"];
if([[NSFileManager defaultManager] fileExistsAtPath:soundFilePath)
{
NSURL *fileURL = [[NSURL alloc] initFileURLWithPath:soundFilePath];
if(fileURL)
{
self.player2 = [[AVAudioPlayer alloc] initWithContentsOfURL:fileURL error:nil];
self.player2.delegate = self;
self.player2.volume = 0.5f;
[self.player2. play];
}
}
else {
NSLog(#"File DoesNot Exists");
}

iOS UITableView Only Reloads Cell Data When Scrolling

I am working on my first Objective-C app for iOS and am having an issue with reloading the data in a UITableView.
After reloading the data the cell content will only update when the cell is scrolled above of below the viewable area of the container.
Here is my .h code:
#import <UIKit/UIKit.h>
#import "AFHTTPClient.h"
#import "AFJSONRequestOperation.h"
#interface HelloWorldViewController : UIViewController <UITextFieldDelegate, UITableViewDelegate, UITableViewDataSource>{
NSMutableArray *tableViewArray;
IBOutlet UITableView *tableView;
}
#property (nonatomic, retain) NSMutableArray *tableViewArray;
#property (weak, nonatomic) IBOutlet UILabel *connectionLabel;
#property (nonatomic, retain) IBOutlet UITableView *tableView;
#property (weak, nonatomic) IBOutlet UITextView *textArea;
#property (weak, nonatomic) IBOutlet UITextField *textField2;
#property (weak, nonatomic) IBOutlet UILabel *label;
#property (weak, nonatomic) IBOutlet UITextField *textField;
#property (copy, nonatomic) NSString *userName;
#property (copy, nonatomic) NSString *passWord;
#property (copy, nonatomic) NSMutableString *serverResponse;
- (IBAction)callHome:(id)sender;
#end
and .m code:
#import "HelloWorldViewController.h"
#interface HelloWorldViewController ()
#end
#implementation HelloWorldViewController
#synthesize tableViewArray;
#synthesize connectionLabel;
#synthesize userName = _userName;
#synthesize passWord = _password;
#synthesize serverResponse = _serverResponse;
#synthesize tableView;
#synthesize textArea;
#synthesize textField2;
#synthesize label;
#synthesize textField;
- (void)viewDidLoad
{
[super viewDidLoad];
tableViewArray = [[NSMutableArray alloc] init];
[tableViewArray addObject:#"TEST1"];
[tableViewArray addObject:#"TEST2"];
[tableViewArray addObject:#"TEST3"];
}
- (void)viewDidUnload
{
[self setTextField:nil];
[self setLabel:nil];
[self setTextField2:nil];
[self setTextArea:nil];
[self setTableView:nil];
[self setConnectionLabel:nil];
[super viewDidUnload];
}
- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
if ([[UIDevice currentDevice] userInterfaceIdiom] == UIUserInterfaceIdiomPhone) {
return (interfaceOrientation != UIInterfaceOrientationPortraitUpsideDown);
} else {
return YES;
}
}
- (BOOL)textFieldShouldReturn:(UITextField *)theTextField {
if (theTextField == self.textField) {
[theTextField resignFirstResponder];
}
return YES;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
return [tableViewArray count];
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
static NSString *CellIdentifier = #"Cell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];
cell.textLabel.text = [self.tableViewArray objectAtIndex: [indexPath row]];
return cell;
}
- (IBAction)callHome:(id)sender {
self.userName = self.textField.text;
self.passWord = self.textField2.text;
NSMutableString *tempResponse = [[NSMutableString alloc] initWithFormat:#""];
AFHTTPClient *client = [[AFHTTPClient alloc] initWithBaseURL:[NSURL URLWithString:#"http://example.com/"]];
[client setAuthorizationHeaderWithUsername:self.userName password:self.passWord];
[client getPath:#"login.do" parameters:nil
success:^( AFHTTPRequestOperation *operation , id responseObject ){
NSLog(#"Authentication Success: %d", operation.response.statusCode);
self.serverResponse = [NSMutableString stringWithFormat:#"Authentication Success: %d", operation.response.statusCode ];
[tempResponse appendString: self.serverResponse];
self.textArea.text = tempResponse;
}
failure:^(AFHTTPRequestOperation *operation , NSError *error){
NSLog(#"Authentication Error: %#\n%#", error, operation);
}
];
[client getPath:#"test.json.do" parameters:nil
success:^( AFHTTPRequestOperation *operation , id responseObject ){
NSLog(#"Retrieval Success: %d", operation.response.statusCode);
NSDictionary *results = [operation.responseString JSONValue];
NSMutableArray *buildings = [results objectForKey:#"buildings"];
NSMutableArray *names = [[NSMutableArray alloc] init];
for (NSDictionary *building in buildings)
{
[names addObject:[building objectForKey:#"name"]];
}
self.tableViewArray = names;
self.serverResponse = [NSMutableString stringWithFormat:#"\nBuilding List Retrieval Success: %d", operation.response.statusCode ];
[tempResponse appendString: self.serverResponse];
self.connectionLabel.text = tempResponse;
}
failure:^(AFHTTPRequestOperation *operation , NSError *error){
NSLog(#"Retrieval Error: %#\n%#", error, operation);
}
];
NSLog(#"tableView is: %#", [tableView description]);
[tableView reloadData];
}
#end
When I call [self.tableView description]the result is null, but if I call it from cellForRowAtIndexPath then I get the following result:
tableView is: <UITableView: 0x8a71000; frame = (0 0; 280 191); clipsToBounds = YES; autoresize = W+H; layer = <CALayer: 0x6b7e860>; contentOffset: {0, 0}>. Delegate: HelloWorldViewController, DataSource: HelloWorldViewController
Here's a screenshot of interface builder:
All help is appreciated! Thanks!
You're probably not connecting the UITableView in the interface builder..
You have to drag while pressing ctrl from the file's owner to the UITableView and connect it.
Also, you should not access your properties without self, you should do:
#synthesize tableViewArray = _tableViewArray;
and then access it with:
self.tableViewArray
try to avoid accessing your ivars directly, use the property!
Good luck!
It looks like you may have not hooked up your UITableView with the HelloWorldViewController tabelView property in IB.