Stopping Background Music when switching to new view

Discussion in 'iOS Programming' started by Wellington2k, Jun 19, 2011.

  1. Wellington2k macrumors regular

    Joined:
    Jun 4, 2011
    #1
    I've been coding an app so that at the title screen music plays and when you tap to start the background music stops. How do I do that? I've tried lots of forums and none work. Here's my code to get the background music to start.


    Code:
    - (void)viewDidLoad {
        NSString *path = [[NSBundle mainBundle] pathForResource:@"hrintro" ofType:@"wav"];
        AVAudioPlayer* theAudio= [[AVAudioPlayer alloc] initWithContentsOfURL:[NSURL fileURLWithPath:path] error:NULL];
        theAudio.delegate = self;
        [theAudio play];
        theAudio.numberOfLoops = 0;
    	
        [super viewDidLoad];
    }
    I'd like very detailed information for the solution.

    Thanks!
     
  2. xStep macrumors 68000

    Joined:
    Jan 28, 2003
    Location:
    Less lost in L.A.
    #2
    What have you tried?

    Have you tried the stop method with your theAudio object?
     
  3. Wellington2k thread starter macrumors regular

    Joined:
    Jun 4, 2011
    #3
    I believe I did, but I kept getting errors. How do you do it?
     
  4. xStep macrumors 68000

    Joined:
    Jan 28, 2003
    Location:
    Less lost in L.A.
    #4
    Did you or didn't you?

    What errors?

    I'm assuming the music does in fact play.

    Where and when are you trying to stop the audio? For instance, in the same object or another one like a new UIViewController?

    Lets see the code block for the stop. Responders will need to understand more of the flow and related objects to be able to help.

    Right now I'm assuming that you have a UIViewController as the first screen and the code you have supplied so far is in that object. When you tap, you call a method in that same object that will load another UIViewController and it is there that you want to stop the music. In that method right at the beginning I'd try inserting this line;
    Code:
    [theAudio stop];
    I'd also place NSLog statements before and after it just to see if you get around this line of code.


    A couple of other notes...

    You've set the delegate for the player, so the obvious question is; have you coded any of the delegate methods. The docs say they are all optional so I doubt that actually matters, but if you haven't coded any of them, there is no need to set the delegate.

    By the way, since the property numberOfLoops defaults to zero, there is no need to set it. Also, you would normally set such a property before sending the play message.
     
  5. robbieduncan Moderator emeritus

    robbieduncan

    Joined:
    Jul 24, 2002
    Location:
    London
    #5
    You are leaking theAudio in viewDidLoad. I'd sort that before I went any further.
     
  6. xStep macrumors 68000

    Joined:
    Jan 28, 2003
    Location:
    Less lost in L.A.
    #6
    How is he leaking theAudio? If he is going to stop it later, he'll need that ivar. OH! It isn't an ivar! I missed that. :eek:
     
  7. robbieduncan Moderator emeritus

    robbieduncan

    Joined:
    Jul 24, 2002
    Location:
    London
    #7
    Lol, exactly. I'd expect that he would want to have a theAudio property, set it and the release that reference in dealloc. We see none of that.
     
  8. Wellington2k thread starter macrumors regular

    Joined:
    Jun 4, 2011
    #8
    Sorry I wasn't specific enough.

    O.K. I have where the background music plays at the title screen.I want that when you switch views the background music stops.
    I do not know specifically what I tried and I'm a beginner to Objective-C.
     
  9. xStep, Jun 19, 2011
    Last edited: Jun 20, 2011

    xStep macrumors 68000

    Joined:
    Jan 28, 2003
    Location:
    Less lost in L.A.
    #9
    Wellington2k, you have a lot to learn. If you don't have a good book, get one. If you can't afford it, check you local library. At minimum read about Objective-C via one of these links;



    You need to understand variable scope. The short description is; Scope is when and where a variable can be accessed. In your original sample robbieduncan noticed that the scope was limited to the viewDidLoad method. The reason was because you declared the variable within that method. By declaring the variable as in instance variable (ivar), the scope expands to all instance methods within an object.

    I've moved the 'theAudio' variable into the interface file. So now we can apply the stop method in another method to 'theAudio' object and it won't crash. To represent your touch I've simply placed an action method called myTap: into this sample so that you can see how we access your audio in two different methods.

    I've hi-lighted in red your current issue.


    With the change your interface file should look a little like this;
    Code:
    @interface MainViewController : UIViewController <AVAudioPlayerDelegate> {
    	[COLOR="Red"]AVAudioPlayer* theAudio;[/COLOR]
    }
    
    - (IBAction) myTap: (id) sender;
    
    @end
    



    This is roughly what your implementation file might look like;
    Code:
    #import "MainViewController.h"
    @implementation MainViewController
    - (void)viewDidLoad {
        NSString *path = [[NSBundle mainBundle] pathForResource:@"hrintro" ofType:@"wav"];
    
        [COLOR="DarkRed"]// We do NOT declare the variable here. We assign the id returned by the creation & init pattern.[/COLOR]
        [COLOR="red"]theAudio[/COLOR] = [[AVAudioPlayer alloc] initWithContentsOfURL:[NSURL fileURLWithPath:path] error:NULL];
        theAudio.delegate = self;
    	theAudio.numberOfLoops = 0;
    
        [COLOR="Red"][theAudio play];[/COLOR]
    
        [super viewDidLoad];
    }
    
    
    - (IBAction) myTap: (id) sender
    {
        [COLOR="Red"][theAudio stop];[/COLOR]
    
        // Some other code to bring up your next view etc.
    }
    
    - (void)dealloc {
        [COLOR="red"][theAudio release];[/COLOR]
        [super dealloc];
    }
    
    

    NOTE: You may want to place the 'play' method call into the viewWillAppear: method but I'll let you learn why. If you do, also note, you'll have to handle the 'path' differently than you do now.
     
  10. Wellington2k, Jun 20, 2011
    Last edited: Jun 21, 2011

    Wellington2k thread starter macrumors regular

    Joined:
    Jun 4, 2011
    #10
    Thanks for the links!
    But now I have 11 errors.
     
  11. robbieduncan Moderator emeritus

    robbieduncan

    Joined:
    Jul 24, 2002
    Location:
    London
    #11
    You have two interface definitions in one .h file. That is very unusual to say the least.
     
  12. Wellington2k thread starter macrumors regular

    Joined:
    Jun 4, 2011
    #12
    Alright, thanks robbieduncan.

    I now have 10 errors.
     
  13. robbieduncan Moderator emeritus

    robbieduncan

    Joined:
    Jul 24, 2002
    Location:
    London
    #13
    So look at the first error. Read it carefully. It will tell you exactly what is wrong. You need to be able to read, understand and fix errors if you are going to do any programming.
     
  14. Wellington2k thread starter macrumors regular

    Joined:
    Jun 4, 2011
  15. xStep macrumors 68000

    Joined:
    Jan 28, 2003
    Location:
    Less lost in L.A.
    #15
  16. Wellington2k thread starter macrumors regular

    Joined:
    Jun 4, 2011
    #16
    Well then could you help explain Step By Step how to do it?

    Sorry. I'm just a beginner. :(
     
  17. robbieduncan Moderator emeritus

    robbieduncan

    Joined:
    Jul 24, 2002
    Location:
    London
    #17
    The post with code in this thread already does that. You need to keep a reference to theAudio to enable you to stop it.

    What have you used to learn basic programming? Not Objective-C specifically, but overall basic concepts. What does variable scope mean? If you don't know this you need to learn more basics before you start actually writing any code.
     
  18. Wellington2k thread starter macrumors regular

    Joined:
    Jun 4, 2011
    #18
    I have 2 errors left now.

    Method definition not in @implementation context

    and

    Expected ';' before '{' token

    And I've used several books to learn. But I forgot what Variable Scope meant.
    I have an app on Cydia, to let you know. It's called HR Quotes Soundboard.

    To get this clear I know almost absolutely second to none about Objective-C, but I've been learning
    everyday.
     
  19. robbieduncan Moderator emeritus

    robbieduncan

    Joined:
    Jul 24, 2002
    Location:
    London
    #19
    You didn't answer the question: what does variable scope mean?

    The first error explains itself perfectly: you have defined a method outside of an @implementation … @end block.
     
  20. Wellington2k thread starter macrumors regular

    Joined:
    Jun 4, 2011
    #20
    Now I have 3 errors.

    Two of the second one in the last reply and

    Expected identifier or '(' before '{' token

    Variable Scope means that once a variable has been declared it mighty not be accessible to other sections of the program code. This accessibility depends on where and how the variable was declared and where the code is that needs to access it.
     
  21. dejo Moderator

    dejo

    Staff Member

    Joined:
    Sep 2, 2004
    Location:
    The Centennial State
    #21
    You continue to post errors with no context. Unfortunately, we are not mind-readers. Without also posting the related code that is generating the errors, as well as indicating which lines the compiler is choking on, it is almost impossible for us to help you troubleshoot your problems. And by "related" code, I don't just mean the specific lines, but more properly the entire method and/or interface and implementation files.

    Regardless, when the compiler complains "Expected ';' before '{' token", what do you think could be the cause?
     
  22. Wellington2k thread starter macrumors regular

    Joined:
    Jun 4, 2011
    #22
    I tried putting ( before { it just gave me the same error.
    I really thought this would be simple and easy.

    Here are the lines of code with the Expected '(' before '{' token error:

    Code:
    -(IBAction)switchback:(id)sender; {
    	Homestar_SFXViewController *second = [[Homestar_SFXViewController alloc] initWithNibName:nil bundle:nil];
    	second.modalTransitionStyle = UIModalTransitionStyleFlipHorizontal;
    	[self presentModalViewController:second animated:YES];
    }
    Here is the code with the Expected ';' before '{' token error:

    Code:
    - (void)viewDidLoad {
        NSString *path = [[NSBundle mainBundle] pathForResource:@"hrintro" ofType:@"wav"];
        theAudio = [[AVAudioPlayer alloc] initWithContentsOfURL:[NSURL fileURLWithPath:path] error:NULL];
        theAudio.delegate = self;
    	theAudio.numberOfLoops = 0;
    	
        [theAudio play];
    	
        [super viewDidLoad];
    }
     
  23. xStep macrumors 68000

    Joined:
    Jan 28, 2003
    Location:
    Less lost in L.A.
    #23
    We are not here to spend our valuable time giving you step-by-step instructions on every little minor problem. Go to school, or read an appropriate Objective-C introduction from cover to cover.

    Your last few questions are the type of things people learn-by-doing. You have to invest time figuring this stuff out on your own. That is how you learn to not make the same mistakes in the future and to know how to fix them when you do.

    Asking for help about every little error is an act of spamming the forum.
     
  24. dejo Moderator

    dejo

    Staff Member

    Joined:
    Sep 2, 2004
    Location:
    The Centennial State
    #24
    First, it would be nice when I ask for not just related code but also indications of which lines are generating the errors, that you provide that requested information. Please be courteous to those trying to help you.

    And why do you think putting a ( before { would fix the error? Are you understanding what changes you are making, or are you just taking a stab in the dark and hope something works?

    It probably is, but I suspect you don't understand the fundamentals of Objective-C enough to debug your own code. Since you claim to be very new at Objective-C programming, perhaps it is time to step away from the real coding and go learn the basics.

    You don't see anything syntactically wrong with the line I've highlighted?

    This code looks fine on its own, but without knowing more context (like, which file contains it, surrounding code, etc.), it's hard to make a determination as to the cause of the error.
     
  25. chown33, Jun 20, 2011
    Last edited: Jun 20, 2011

    chown33 macrumors 604

    Joined:
    Aug 9, 2009
    #25
    Compiler errors that have the form "Expected X before Y" usually occur because something is very wrong with the syntax. The X that the compiler says it's expecting before Y may not be the solution to the problem. It's often just a hopelessly confused compiler guessing what you meant, at the point where the syntax broke down.

    "Very wrong" can mean a single extra semicolon or other punctuation. Or a single missing semicolon or other punctuation.

    Often enough, the line where the compiler complains about the error won't actually contain an error. The real error lies some number of lines BEFORE the line with the reported error. That's why the code that comes BEFORE a reported error is important to see when debugging.

    And the real error might not even be in the same file. It might be at the end of an imported file, and the error doesn't occur until some point after the #import.
     

Share This Page