Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to play a sound in objective C iphone coding

I have an app I am working on and It uses some of the hardware sensors to provide data on screen, there is a Label that updates with the number. I want a sound to play whenever the number is above 100 or something. For example, say it was reading numbers then all of the sudden it finds a good spot (or whatever), then I would like a sound to play or a light to light up. I am an absolute beginner and it would be nice if the answer would be easy for a absolute beginner to understand.

like image 750
DanielsCaleb0 Avatar asked Dec 03 '22 10:12

DanielsCaleb0


1 Answers

I am using the system AudioToolbox.framework for playing sounds in my simple game. I added this static function to common MyGame class:

+ (SystemSoundID) createSoundID: (NSString*)name
{
  NSString *path = [NSString stringWithFormat: @"%@/%@",
                     [[NSBundle mainBundle] resourcePath], name];


  NSURL* filePath = [NSURL fileURLWithPath: path isDirectory: NO];
  SystemSoundID soundID;
  AudioServicesCreateSystemSoundID((__bridge CFURLRef)filePath, &soundID);
  return soundID;
} 

I added the "Morse.aiff" file to project Resources and initialized it in (any) class initialization with the following:

self.mySound = [MyGame createSoundID: @"Morse.aiff"];

And then I played sound with this call:

AudioServicesPlaySystemSound(mySound);

Also, don't forget to import AudioServices.h file.

This audio toolbox can play also different sound formats.

like image 59
Krešimir Prcela Avatar answered Dec 15 '22 17:12

Krešimir Prcela