简体   繁体   中英

Button not playing audio in iOS

I uploaded a file audio.wav into my supporting files folder.

This is my PlayAudio.h

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

@interface PlayAudio : UIViewController {

}

-(IBAction) PlayIt;

@end

This is my PlayAudio.m after the implementation command

- (IBAction) PlayIt; {
    CFBundleRef mainBundle = CFBundleGetMainBundle();
    CFURLRef soundFileURLRef;
    soundFileURLRef = CFBundleCopyResourceURL(mainBundle, (CFStringRef) @"audio", CFSTR ("wav"), NULL);
    UInt32 soundID;
    AudioServicesCreateSystemSoundID(soundFileURLRef, &soundID);
    AudioServicesPlaySystemSound(soundID);

}

I then ctrl-clicked from the play button to the First Responder in my view controller and selected PlayIt. I see it's associated with Touch Up Inside.

For some reason I can click the button, but nothing plays. I'm doing this in Storyboard.

You can use NSURL to get the path of your wav file and cast it to CFURLRef, check the following code:

SystemSoundID soundID;
NSURL *soundPath = [NSURL fileURLWithPath:[[NSBundle mainBundle] pathForResource:@"audio" ofType:@"wav"]];
if (AudioServicesCreateSystemSoundID ((CFURLRef)soundPath, &soundID) != kAudioServicesNoError) {
     AudioServicesPlayAlertSound(soundID);

}

Note, that if mute button on iphone is enable AudioServicesCreateSystemSoundID function will fail(Vibration can be used in this case:soundID = kSystemSoundID_Vibrate;). If you want to play sound disregarding the mute switch, use AVAudioPlayer api.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM