How to add sound to Xcode project

How to add sound to Xcode IOS project


How to add sound to Xcode project. This how to start and stop music and sound effects in your IOS Xcode project.



Add Sound files
When adding sounds file to your Xcode project, don't forget to check "Copy items into destination group's folder". In this example, our sound is called MusicFileOne.mp3



Add AVFoundation.framework
To install, go to Build Phases - Link Binary and add AVFoundation.framework.



Import AVFoundation.framework to .h file
The code should look like this:

#import <AVFoundation/AVFoundation.h>



Add this to your .m file
Copy/Paste this into your .m file

@interface ViewController ()

@property (nonatomic, strong) AVAudioPlayer *audioPlayer;
@property (nonatomic) BOOL SoundOne;

@end
@implementation ViewController

- (void)viewDidLoad
{
[super viewDidLoad];

self.SoundOne = NO;
NSBundle *mainBundle = [NSBundle mainBundle];
NSString *filePath = [mainBundle pathForResource:@"MusicFileOne" ofType:@"mp3"];
NSData *fileData = [NSData dataWithContentsOfFile:filePath];
NSError *error = nil;
self.audioPlayer = [[AVAudioPlayer alloc] initWithData:fileData error:&error];
[self.audioPlayer prepareToPlay];
}



Start Sound
Add this where you want to start the music:

[self.audioPlayer play];
self.SoundOne = YES;



Stop Sound
add this where you want to stop the sounds

[self.audioPlayer stop];
self.SoundOne = NO;


IOS Xcode App Help
Read other useful IOS Apps articles for Xcode developers.








 
 
Copyright  |   Privacy Policy  |   Social Media  |   Disclaimer  |   Directory  |   Contact  |   Advertise  |   Search