Search code examples
iosaudioxcode4xcode4.3

playing audio when apps running


I've been trying lately to get my app to play a sound from when it open to when its closed and I'm have difficulty. I have some code on playing a sound when I press a button and it's fine I'm just wondering if there is any tweaks I could do to make it play on its own and from the start or is there a way I could say press play and make the sound loop why I'm playing the game.

.h

#import <AudioToolbox/AudioToolbox.h>


    - (IBAction)t1:(id)sender;

.m

- (IBAction)t1:(id)sender {

    CFBundleRef mainbundle = CFBundleGetMainBundle();
    CFURLRef soundFileUrlRef;
    soundFileUrlRef = CFBundleCopyResourceURL(mainbundle, (CFStringRef) @"t1", CFSTR ("wav"), NULL); 
    UInt32 soundID;
    AudioServicesCreateSystemSoundID(soundFileUrlRef, &soundID);
    AudioServicesPlaySystemSound(soundID);
}

Solution

  • how about trying AVAudioPlayer and turning on the continuous playback by setting number of loops to -1:

        myPlayer.numberOfLoops = -1
    
        [myPlayer prepareToPlay];
    
        [myPlayer play];
    
    
        //when application did enter background or something
        [myPlayer stop];
    

    http://developer.apple.com/library/ios/#DOCUMENTATION/AVFoundation/Reference/AVAudioPlayerClassReference/Reference/Reference.html

    Also make sure your Audio Sessions are set properly for background playback: http://developer.apple.com/library/ios/#DOCUMENTATION/Audio/Conceptual/AudioSessionProgrammingGuide/Basics/Basics.html#//apple_ref/doc/uid/TP40007875-CH2-SW2