Advertise Mobile SDKs Books Events Forum News Social Networking Support Us
Follow @iphonedevsdk on Twitter

Interface 2, Advanced iOS
Mockup & Code Gen
($9.99)

Make your own iPhone apps
and run them live!
(free)

Pic Frame Dynamo: Photo Editing
($0.99)

Abiliator
($1.99)

Want your application or service advertised on iPhone Dev SDK?

Go Back   iPhone Dev SDK Forum > iPhone SDK Development Forums > iPhone SDK Development

Reply
 
LinkBack Thread Tools Display Modes
Old 08-22-2011, 08:45 AM   #1 (permalink)
Registered Member
 
Join Date: Aug 2011
Posts: 9
penpaper is on a distinguished road
Question Audio Switch on off possibility in IBAction?

Hello readers

I was searching through the threads and found some topics about implementing a void function to switch the audio on off. This is entirely new to me, since i am using this code right here:

- (IBAction)m1 {
NSString *path = [[NSBundle mainBundle] pathForResource:@"Audio1" ofType:@"mp3"];
AVAudioPlayer* theAudio = [[AVAudioPlayer alloc] initWithContentsOfURL:[NSURL fileURLWithPath:path] error:NULL];
theAudio.delegate = self;
[theAudio play];
}

This plays my audio. What I am asking though is if there is a way of making the audio file go on/off by switching one of those light blue switches in the Interface builder somehow. I would still really like to use my IBAction though, because that is what I understand right now at the moment.

Thanks you in advance
penpaper is offline   Reply With Quote
Old 08-22-2011, 11:02 AM   #2 (permalink)
Fly-by-night Innovator
 
Join Date: Jun 2010
Posts: 364
musicwind95 is on a distinguished road
Default

Have a switch as an IBOutlet. Then, connect the switch's Value Changed connection to your IBAction. Check for the switch's on property.

Code:
// Controller.m
@synthesize audioControlSwitch;


- (IBAction)toggleAudio {
    if (audioControlSwitch.on) {
        NSString *path = [[NSBundle mainBundle]   pathForResource:@"Audio1" ofType:@"mp3"];
        AVAudioPlayer* theAudio = [[AVAudioPlayer alloc] initWithContentsOfURL:[NSURL fileURLWithPath:path] error:NULL];
        theAudio.delegate = self;
        [theAudio play];
    }
    else {
        // Stop playing
    }
}
__________________
If I have helped you, please consider donating. I use PayPal. It would mean a lot to me!


For more iOS Development, check out my blog—Cups of Cocoa. All visitors welcome, but especially beginners!

Hope I have helped!

Please check out IceFall, a new action game available in the App Store!

Last edited by musicwind95; 08-22-2011 at 11:04 AM. Reason: Code sample
musicwind95 is offline   Reply With Quote
Old 08-22-2011, 11:11 AM   #3 (permalink)
Just helping out.
 
Domele's Avatar
 
Join Date: Feb 2011
Posts: 2,565
Domele is on a distinguished road
Default

Won't work. You'll lose your reference to your audio player. You need to make your AVAudioPlayer an instance variable.
__________________
If you are looking for a quality developer, I'm your man. Give me a PM if you are interested.

New app - See screenshots and details at www.globaclock.com.

If you want to thank me, click the link. Every click counts. If you want to do more, buy my app. A link is available on my website. Thanks.
Domele is offline   Reply With Quote
Old 08-22-2011, 02:29 PM   #4 (permalink)
Registered Member
 
Join Date: Aug 2011
Posts: 9
penpaper is on a distinguished road
Post

Thank you two for replying this fast!

musicwind95: you said that I should have an IBAction of the 'toggle Audio'. I created one in my h file, and posted your code into my m file. I linked the action to my blue switch, and clicked on touch up inside. How do I link my button to the 'audioControlSwitch'? Is that another ViewController? Or do I just rename my switch to audioControl Switch?

Domele: didn't musicwind95 include the AVAudioPlayer though? Everything should still work, because we still get the audio through the AVAudioPlayer. Thats what I believe at least.......

Thank you,
penpaper is offline   Reply With Quote
Old 08-22-2011, 02:50 PM   #5 (permalink)
Fly-by-night Innovator
 
Join Date: Jun 2010
Posts: 364
musicwind95 is on a distinguished road
Default

Quote:
Originally Posted by penpaper View Post
Thank you two for replying this fast!

musicwind95: you said that I should have an IBAction of the 'toggle Audio'. I created one in my h file, and posted your code into my m file. I linked the action to my blue switch, and clicked on touch up inside. How do I link my button to the 'audioControlSwitch'? Is that another ViewController? Or do I just rename my switch to audioControl Switch?
audioControlSwitch was just a dummy name. You could just rename your switch to that, make sure it's an IBOutlet, and connect to that. One thing though—you should connect's the switch's Value Changed to toggleAudio, rather than Touch Up Inside.

Quote:
Originally Posted by penpaper View Post
Domele: didn't musicwind95 include the AVAudioPlayer though? Everything should still work, because we still get the audio through the AVAudioPlayer. Thats what I believe at least.......
Thank you,
No, Domele's right. The AVAudioPlayer is limited to that first if() block. At least declare it right inside the method, but outside of the if() block.

Code:
- (IBAction)toggleAudio {
    AVAudioPlayer* theAudio = [[AVAudioPlayer alloc] initWithContentsOfURL:[NSURL fileURLWithPath:path] error:NULL];
    if (audioControlSwitch.on) {
        NSString *path = [[NSBundle mainBundle]   pathForResource:@"Audio1" ofType:@"mp3"];
        theAudio.delegate = self;
        [theAudio play];
    }
    else {
        // Stop playing
    }
}
__________________
If I have helped you, please consider donating. I use PayPal. It would mean a lot to me!


For more iOS Development, check out my blog—Cups of Cocoa. All visitors welcome, but especially beginners!

Hope I have helped!

Please check out IceFall, a new action game available in the App Store!

Last edited by musicwind95; 08-22-2011 at 02:54 PM. Reason: Added code example
musicwind95 is offline   Reply With Quote
Old 08-22-2011, 03:05 PM   #6 (permalink)
Registered Member
 
Join Date: Aug 2011
Posts: 9
penpaper is on a distinguished road
Post

Hi Thanks for replying.

I made my switch an IBOutlet like this

IBOutlet UISwitch *audioControlSwitch;

in my header file, and connected it in my .xib file. The only problem is the code. The part above the if statement has the

[NSURL fileURLWithPathath]

in it. I get an error that the path is undeclared. I don't really understand this, because the code I use (which was stated earlier way above) uses the exact same code, just a little bit more down (like the third line). Do you know what the reason for this error could be?

Thank you,
penpaper is offline   Reply With Quote
Old 08-22-2011, 03:31 PM   #7 (permalink)
Registered Member
 
Join Date: Aug 2011
Posts: 9
penpaper is on a distinguished road
Question Partly Solved

Nevermind, i solved that problem by implementing one line a little further up. My code now looks like this

- (IBAction)toggleAudio {
NSString *a = [[NSBundle mainBundle] pathForResource:@"Audio1" ofType:@"mp3"];
AVAudioPlayer* theAudio = [[AVAudioPlayer alloc] initWithContentsOfURL:[NSURL fileURLWithPath:a] error:NULL];
if (audioControlSwitch.on) {

theAudio.delegate = self;
[theAudio play];
}
else {
// Stop playing
if (audioControlSwitch.off) {

theAudio.delegate = self;
[theAudio stop];
}
}
}

I can't get the music to stop playing though once I started it. I tried with the if audioControl Switch off, but xcode doesn't recognize 'off'. So what should I do now??

Thanks in advance,
penpaper is offline   Reply With Quote
Old 08-22-2011, 04:36 PM   #8 (permalink)
Fly-by-night Innovator
 
Join Date: Jun 2010
Posts: 364
musicwind95 is on a distinguished road
Default

Quote:
Originally Posted by penpaper View Post

I can't get the music to stop playing though once I started it. I tried with the if audioControl Switch off, but xcode doesn't recognize 'off'. So what should I do now??
The property's name doesn't change to off. Try something like this:

Code:
if (audioControlSwitch.on) {
    // Switch is 'on': start playing
}
else {
    // Switch is 'off': stop playing
}
__________________
If I have helped you, please consider donating. I use PayPal. It would mean a lot to me!


For more iOS Development, check out my blog—Cups of Cocoa. All visitors welcome, but especially beginners!

Hope I have helped!

Please check out IceFall, a new action game available in the App Store!
musicwind95 is offline   Reply With Quote
Old 08-22-2011, 05:38 PM   #9 (permalink)
Just helping out.
 
Domele's Avatar
 
Join Date: Feb 2011
Posts: 2,565
Domele is on a distinguished road
Default

Your code will never stop the audio because you are losing your reference to your original audio player. That is what I meant by it's not going to work. Every time that method runs you are creating a new audio player object, one that is independent of the one you created before. That is why you need to create an instance variable and assign your audio player to that so you can keep a reference to it and give it a stop message when needed.
__________________
If you are looking for a quality developer, I'm your man. Give me a PM if you are interested.

New app - See screenshots and details at www.globaclock.com.

If you want to thank me, click the link. Every click counts. If you want to do more, buy my app. A link is available on my website. Thanks.
Domele is offline   Reply With Quote
Old 08-22-2011, 05:48 PM   #10 (permalink)
Cocoa Junkie
 
Duncan C's Avatar
 
Join Date: Dec 2008
Location: Northern Virginia
Posts: 6,003
Duncan C has a spectacular aura about
Default

Quote:
Originally Posted by penpaper View Post
Nevermind, i solved that problem by implementing one line a little further up. My code now looks like this

- (IBAction)toggleAudio {
NSString *a = [[NSBundle mainBundle] pathForResource:@"Audio1" ofType:@"mp3"];
AVAudioPlayer* theAudio = [[AVAudioPlayer alloc] initWithContentsOfURL:[NSURL fileURLWithPath:a] error:NULL];
if (audioControlSwitch.on) {

theAudio.delegate = self;
[theAudio play];
}
else {
// Stop playing
if (audioControlSwitch.off) {

theAudio.delegate = self;
[theAudio stop];
}
}
}

I can't get the music to stop playing though once I started it. I tried with the if audioControl Switch off, but xcode doesn't recognize 'off'. So what should I do now??

Thanks in advance,

As Domele says, you should not create the audio player in the IBAction.

Make your audio player theAudio a retained property.
Create your audio player in your viewDidLoad method, and save it to the property. Then set the property to nil in your viewDidUnload method.

Code:
- (void) viewDidLoad;
{
  NSString *a = [[NSBundle mainBundle]   pathForResource:@"Audio1" ofType:@"mp3"];
  self.theAudio = [[[AVAudioPlayer alloc] 
    initWithContentsOfURL: [NSURL fileURLWithPath:a] 
    error:NULL] autorelease];
  [self.theAudio prepareToPlay];
}
In your IBAction, simply start/stop the sound:


Code:
- (IBAction)toggleAudio 
{
  if (audioControlSwitch.on) 
 {
    [self.theAudio play];
  }
  else
  {
    [self.theAudio stop];
  }
}
__________________
Regards,

Duncan C
WareTo

Check out our apps in the Apple App store


Check out this password generator app that shows various techniques including using a data container singleton object to share data between objects in your project.

See this tutorial on using UIView animations and layer animations:

See this thread on generating random, non-repeating text

Check out a very cool Macintosh Kaleidoscopes app called ScopeWorks that we released to the Mac App store.
Duncan C is offline   Reply With Quote
Old 08-23-2011, 04:38 AM   #11 (permalink)
Registered Member
 
Join Date: Aug 2011
Posts: 9
penpaper is on a distinguished road
Question Almost there

Thanks for replying. I'll just go with DuncanC for now, since I only started a few months back, and I have no idea how to code a bunch, just a little.

DuncanC: I understand that I have to do all that. Since I just started out a few months ago, its pretty complicated though. I have a sub view controller. This is the code for the h file:


#import <UIKit/UIKit.h>
#import <AVFoundation/AVFoundation.h>


@interface Family : UIViewController {

IBOutlet UISwitch *audioControlSwitch;
AVAudioPlayer *backaudio;

}

-(IBAction) toggleAudio;

@property(nonatomic,retain) UISwitch *audioControlSwitch;
@property(nonatomic,retain) AVAudioPlayer *backaudio;

@end




and this is my .m file:




#import "Family.h"
#import <AVFoundation/AVFoundation.h>


@implementation Family
@synthesize audioControlSwitch;
@synthesize backaudio;


- (IBAction)toggleAudio
{
if (audioControlSwitch.on)
{
[self.backaudio play];
}
else
{
[self.backaudio stop];
}
}

#pragma mark -
#pragma mark View lifecycle


- (void) viewDidLoad {

self.title = @"Music";

NSString *a = [[NSBundle mainBundle] pathForResource:@"Audio1" ofType:@"mp3"];
self.backaudio = [[[AVAudioPlayer alloc]
initWithContentsOfURL: [NSURL fileURLWithPath:a]
error:NULL] autorelease];
[self.backaudio prepareToPlay];


}

/*
- (void)viewWillAppear:(BOOL)animated {
[super viewWillAppear:animated];
}
*/
/*
- (void)viewDidAppear:(BOOL)animated {
[super viewDidAppear:animated];
}
*/
/*
- (void)viewWillDisappear:(BOOL)animated {
[super viewWillDisappear:animated];
}
*/
/*
- (void)viewDidDisappear:(BOOL)animated {
[super viewDidDisappear:animated];
}
*/
/*
// Override to allow orientations other than the default portrait orientation.
- (BOOL)shouldAutorotateToInterfaceOrientation:(UIIn terfaceOrientation)interfaceOrientation {
// Return YES for supported orientations.
return (interfaceOrientation == UIInterfaceOrientationPortrait);
}
*/


#pragma mark -
#pragma mark Memory management

- (void)didReceiveMemoryWarning {
// Releases the view if it doesn't have a superview.
[super didReceiveMemoryWarning];

// Relinquish ownership any cached data, images, etc. that aren't in use.
}

- (void)viewDidUnload {

self.backaudio = nil;
}


- (void)dealloc {
[super dealloc];
}


@end


And everything works fine! The view just doesn't load from my table view when I build and run. Any idea what could be the problem? (I did everything you said I should, but maybe I did it wrong or something....)

Thanks in advance,

by the way: how do you add code to a reply of a thread? Its probably really hard to read when I just copy and paste.
penpaper is offline   Reply With Quote
Old 08-23-2011, 12:29 PM   #12 (permalink)
Just helping out.
 
Domele's Avatar
 
Join Date: Feb 2011
Posts: 2,565
Domele is on a distinguished road
Default

Code tags. [code] [1/CODE] without the 1.
__________________
If you are looking for a quality developer, I'm your man. Give me a PM if you are interested.

New app - See screenshots and details at www.globaclock.com.

If you want to thank me, click the link. Every click counts. If you want to do more, buy my app. A link is available on my website. Thanks.
Domele is offline   Reply With Quote
Old 08-23-2011, 03:22 PM   #13 (permalink)
Registered Member
 
Join Date: Aug 2011
Posts: 9
penpaper is on a distinguished road
Post Audio Code with Code in 'Code-Format'

allright so this is my code. Both of them are in a subviewcontroller that gets loaded once i tap on my Navigation Controller's table view.

Code:
#import <UIKit/UIKit.h>
#import <AVFoundation/AVFoundation.h>


@interface Family : UIViewController {

	IBOutlet UISwitch *audioControlSwitch;
	AVAudioPlayer *backaudio;

}

-(IBAction) toggleAudio;

@property(nonatomic,retain) UISwitch *audioControlSwitch;
@property(nonatomic,retain) AVAudioPlayer *backaudio;

@end

and this is my .m file:



Code:
#import "Family.h"
#import <AVFoundation/AVFoundation.h>


@implementation Family
@synthesize audioControlSwitch;
@synthesize backaudio;


- (IBAction)toggleAudio 
{
	if (audioControlSwitch.on) 
	{
		[self.backaudio play];
	}
	else
	{
		[self.backaudio stop];
	}
}

#pragma mark -
#pragma mark View lifecycle


- (void) viewDidLoad {
	
	self.title = @"Music";
	
		NSString *a = [[NSBundle mainBundle]   pathForResource:@"Audio1" ofType:@"mp3"];
		self.backaudio = [[[AVAudioPlayer alloc] 
						  initWithContentsOfURL: [NSURL fileURLWithPath:a] 
						  error:NULL] autorelease];
		[self.backaudio prepareToPlay];
	
	
}

/*
- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
}
*/
/*
- (void)viewDidAppear:(BOOL)animated {
    [super viewDidAppear:animated];
}
*/
/*
- (void)viewWillDisappear:(BOOL)animated {
    [super viewWillDisappear:animated];
}
*/
/*
- (void)viewDidDisappear:(BOOL)animated {
    [super viewDidDisappear:animated];
}
*/
/*
// Override to allow orientations other than the default portrait orientation.
- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation {
    // Return YES for supported orientations.
    return (interfaceOrientation == UIInterfaceOrientationPortrait);
}
*/


#pragma mark -
#pragma mark Memory management

- (void)didReceiveMemoryWarning {
    // Releases the view if it doesn't have a superview.
    [super didReceiveMemoryWarning];
    
    // Relinquish ownership any cached data, images, etc. that aren't in use.
}

- (void)viewDidUnload {
	
	self.backaudio = nil;
}


- (void)dealloc {
    [super dealloc];
}


@end
penpaper is offline   Reply With Quote
Old 08-23-2011, 05:38 PM   #14 (permalink)
Cocoa Junkie
 
Duncan C's Avatar
 
Join Date: Dec 2008
Location: Northern Virginia
Posts: 6,003
Duncan C has a spectacular aura about
Default

Quote:
Originally Posted by penpaper View Post
Thanks for replying. I'll just go with DuncanC for now, since I only started a few months back, and I have no idea how to code a bunch, just a little.

DuncanC: I understand that I have to do all that. Since I just started out a few months ago, its pretty complicated though. I have a sub view controller. This is the code for the h file:



And everything works fine! The view just doesn't load from my table view when I build and run. Any idea what could be the problem? (I did everything you said I should, but maybe I did it wrong or something....)

Thanks in advance,

by the way: how do you add code to a reply of a thread? Its probably really hard to read when I just copy and paste.


Your code to load and unload your view controller looks good, as does the toggleAudio method.

You said your view doesn't load from your table view, but you never posted the code from the previous view controller that's supposed to trigger the loading of this one. We can't help debug code we can't see!

Tell us what user action in the previous view controller is supposed to cause this view controller to be displayed, and then show the code that should be displaying it.
__________________
Regards,

Duncan C
WareTo

Check out our apps in the Apple App store


Check out this password generator app that shows various techniques including using a data container singleton object to share data between objects in your project.

See this tutorial on using UIView animations and layer animations:

See this thread on generating random, non-repeating text

Check out a very cool Macintosh Kaleidoscopes app called ScopeWorks that we released to the Mac App store.
Duncan C is offline   Reply With Quote
Old 08-24-2011, 07:57 AM   #15 (permalink)
Registered Member
 
Join Date: Aug 2011
Posts: 9
penpaper is on a distinguished road
Unhappy Link from Nav Controller to View1

Hi Thanks for replying.

Well, I mean everything worked before I implemented the toggle audio action and the part in the viewdidload. But anyways, this is the code I use to get from my table view to my other views.

Code:
This is the code from my RootViewController.m file.

@synthesize v1;

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
	
	if (indexPath.row == 0) {
		
		if(self.v1 == nil) {
			About *View1 =
			[[About alloc] initWithNibName:@"About" bundle:[NSBundle mainBundle]];
			self.v1 = View1;
			[View1 release];	
		}
		[self.navigationController pushViewController:self.v1 animated:YES];
	}
and this is the code in my header file:
Code:
#import <UIKit/UIKit.h>
#import "About.h"

@interface RootViewController : UITableViewController {
	
	About *v1;
}

@property(nonatomic,retain) About *v1;

@end
I got the code for this from a tutorial a while back. Everything works fine with the code, its just that once I added the new code it didn't load all of a sudden.

Obviously this isn't all of the code in my rootviewcontroller, but this is the important code, because the rest is the green code thats always there at the beginning of an application.

Thanks in advance,
penpaper is offline   Reply With Quote
Old 08-25-2011, 04:26 PM   #16 (permalink)
Registered Member
 
Join Date: Aug 2011
Posts: 9
penpaper is on a distinguished road
Question Still not working ! :(

Hi,

so do you (all) think that its the audio player's fault, or the rootviewcontroller to the view's fault? Any idea what I could have done wrong?
penpaper is offline   Reply With Quote
Reply

Bookmarks

Tags
audio, ibaction, switch

Thread Tools
Display Modes

Posting Rules
You may not post new threads
You may not post replies
You may not post attachments
You may not edit your posts

BB code is On
Smilies are On
[IMG] code is On
HTML code is Off
Trackbacks are On
Pingbacks are On
Refbacks are On



» Advertisements
» Online Users: 397
13 members and 384 guests
7twenty7, cristofercolmbos, dedeys78, fiftysixty, gmarro, iOS.Lover, jonathandeknudt, Matrix23, raymng, stanny, tymex, UMAD, xerohuang
Most users ever online was 1,387, 04-10-2012 at 04:21 AM.
» Stats
Members: 175,669
Threads: 94,121
Posts: 402,903
Top Poster: BrianSlick (7,990)
Welcome to our newest member, dedeys78
Powered by vBadvanced CMPS v3.1.0

All times are GMT -5. The time now is 04:13 AM.
Powered by vBulletin® Version 3.8.0
Copyright ©2000 - 2012, Jelsoft Enterprises Ltd.
Search Engine Friendly URLs by vBSEO 3.3.0