No sound

I created a UISwitch. And wants it to control sound. But not work.

@interface SoundViewController ()
{
    AVPlayer *_audioPlayer;
   
}
@end
@implementation SoundViewController
-(IBAction)soundSwitch:(id)sender{
    if (_soundSwitch.on) {
        CFBundleRef mainBundle = CFBundleGetMainBundle();
        CFURLRef soundFileURLRef;
        soundFileURLRef = CFBundleCopyResourceURL(mainBundle, (CFStringRef) @"soundN ame), NULL);
        UInt32 soundID;
        AudioServicesCreateSystemSoundID(soundFileURLRef, &soundID);
        AudioServicesPlaySystemSound(soundID);
    }else
    {
        /
    }
}

No sound is playing. Please help. Thanks

You have a typo on line 12


soundFileURLRef = CFBundleCopyResourceURL(mainBundle, (CFStringRef) @"soundN ame), NULL);


What is @"soundN ame ? Are you sure it is the correct name ?


Did you test that soundFileURLRef is not NULL ?

You should also test the value returned by AudioServicesCreateSystemSoundID, with


OSStatus result;
result = AudioServicesCreateSystemSoundID(soundFileURLRef, &soundID);
// print result

Your answer helps me. Thank you very much. I "import"ed AudioToolBox instead of AVPlayer:

-(IBAction)soundSwitch:(id)sender{
    if (_soundSwitch.on) {
        CFBundleRef mainBundle = CFBundleGetMainBundle();
        CFURLRef soundFileURLRef;
        soundFileURLRef = CFBundleCopyResourceURL(mainBundle, (CFStringRef) @"the sound name", CFSTR ("wav"), NULL);
        UInt32 soundID;
        AudioServicesCreateSystemSoundID(soundFileURLRef, &soundID);
        AudioServicesPlaySystemSound(soundID);
       
    }else
    {
        //I don't write any code here
    }
}

And it works. But the sound doesn't repeat. If I turned off the switch, the sound is still playing. Why? Please help me. I wish you can give sample code me Thanks.

Great.


What do you mean "sound doesn't repeat" ? Does not repeat when what ?

I have the sound in my game, and I have a UISwitch to enable the user to turn on or off the sound. But when I switch it off the sound is still playing. When the sound comes to the end, it stops. I want it to repeat when it stops if the switch is on and stops when the switch is off. How can I do that? Please help me. Thanks

You should keep a reference to the audioPlayer and then call stop or play on it as needed.


Have a look here :


http : / / stackoverflow.com/questions/38409834/swift-stop-avaudioplayer


It is ObjC, but easy to adapt.

For your info, your playground should bè written in Swift.

Thanks for help. But do you have Objective C code?

no, sorry.


but converting a few lines to ObjC should not be that hard.


the key point is to keep a reference you your audio player to be able to stop and play.

No sound
 
 
Q