Simpler Solution For Playing Audio on an iPhone - iphone

Apple lists (http://developer.apple.com/samplecode/AudioQueueTest/listing1.html) as a quick demonstration of playing an audio file.
Is there a way to play an audio file with many less lines of code?

Here's a quick and dirty way to do sounds. It's suitable for playing short sounds with no control over duration, volume or precise timing. With those disclaimers, here we go.
In the view controller that will play the sound, import this framework:
#import <AudioToolbox/AudioToolbox.h>
Then manually add the AudioToolbox framework to your project with: Control-click on Frameworks Group --> Add... --> Existing Frameworks... --> AudioToolbox.framework
Next, add 'someSound.caf' to your project Resources folder, obviously use your actual filename.
Inside the method that plays your sound, add:
SystemSoundID theSound;
AudioServicesCreateSystemSoundID((CFURLRef)[NSURL fileURLWithPath:[[NSBundle mainBundle] pathForResource:#"someSound" ofType:#"caf"]], &theSound);
AudioServicesPlaySystemSound(theSound);
I use this method for prototyping, not for production code, because of it's many limitations.

Related

Play midi file or midi tone in iPhone with Xcode / Cocoa

I need to play midi file or midi tone in iPhone.
I have tested MidiMonitor. I think that I need to create a destination point on the iPhone to receive midi, but I don't know how do it.
Can you help me? Example source code would be useful.
Like #skinnyTOD noted, from iOS 5.0 on it is possible to use MediaPlayer.
First link the AVFoundation, and AudioToolbox frameworks to your project, then use this code:
#import <AVFoundation/AVFoundation.h>
NSURL *midiUrl = [[NSBundle mainBundle] URLForResource:#"even voor mij" withExtension:#"mid"];
MusicPlayer player = NULL;
NewMusicPlayer(&player);
MusicSequence sequence = NULL;
NewMusicSequence(&sequence);
MusicSequenceFileLoad(sequence, (__bridge CFURLRef)midiUrl, NULL, NULL);
MusicPlayerSetSequence(player, sequence);
MusicPlayerStart(player);
This sets up the player with your midi file from bundle, and start playing.
Note that you will need to call DisposeMusicSequence and DisposeMusicPlayer when cleaning up the player.
If you are still trying to sort this, iOS 5 includes the MusicPlayer API - it can load, play and create midi files. You'll need to also read up on the new AUSampler AudioUnit.

Play iPhone camera shutter sound when I click a button

How do I play the shutter sound from iPhone when I click a button?
You can use AudioToolbox and pure magical number 1108 like this:
Swift:
import AudioToolbox
AudioServicesPlaySystemSound(1108)
Objective-C:
#import <AudioToolbox/AudioToolbox.h>
AudioServicesPlaySystemSound(1108);
Here is full list of these pure magical ids.
1) Search online for a camera shutter wave file. You can trim this one if it is a bit long using a .wav editor
http://www.freesound.org/people/Nathan_Lomeli/sounds/79190/
2) Name it shutter.wav and put it into your development directory along with your other resources.
3) Define the sound in your view's .h file
#interface myViewController : UIViewController {
SystemSoundID SoundID;
}
4) Load the file in your View's "viewDidLoad" event:
//load a sound wav file to use for the shutter
NSURL *buttonURL = [NSURL fileURLWithPath:[[NSBundle mainBundle] pathForResource:#"shutter" ofType:#"wav"]];
AudioServicesCreateSystemSoundID((__bridge CFURLRef)buttonURL, &SoundID);
5) In your button_click event:
//play then shutter.wav sound
AudioServicesPlaySystemSound(SoundID);
some sounds to pick to those location : /System/Library/Components/CoreAudio.component/Contents/SharedSupport/SystemSounds
/System/Library/Sounds
You don't specify a programming language, but let's assume ObjC for now and not Monotouch or any other 3rd party framework.
AVAudioPlayer from the AV framework is your friend.
Please see the documentation here at Apple
Or do a search on AVAudioPlayer here on SO and you will find dozens of examples.
Still, you will have to grab the shutter sound file from somewhere but you can take any public available shutter WAV you find on Google.
If you really want to use the camera, the shutter sound will be played automatically when a picture is taken but I doubt that is what you want.

OGG Vorbis in iPhone sdk

I want to know if it's possible to play Ogg Vorbis audio file with iPhone SDK or if exist a library or a framework that allow this.
I've read something about OpenAL but I don't find any tutorial...
Can anyone help me??
Better late than never ;)
I have found the answer here Use cocos2d for playing ogg file in my project?.
PASoundMgr is a different sound engine that had support for ogg file
playback. However, it hasn't been updated since iOS 2.x and there are
numerous issues that have cropped up since then that it doesn't
handle.
Why do you need to play ogg files? If you convert them to aac you will
be able to play them back using hardware decoding which is much more
efficient from a cpu usage point of view.
They mentioned PASoundMgr. It worked for me. I just copied from cocos2d framework all files->libraries that SoundEngineTest was based on. And got rid of unnecessary code.
Here is my demoProject that shows how to play ogg on ios.
Be careful with iOS 5.* simulators, they have some problems with sound library. My demo works on 4.3 simulator and on Device.
Here are steps that I made to create demo:
First you will need cocos2d-iphone framework. I've already had it, but you can find it here cocos-2d_download.
As you can notice SoundEngineTest depends on libvorbis.a. It's a library that made of files from external/Tremor group. Also it depends on OpenAl, AudioToolbox frameworks.
I copied all files from tremor group to my project. Crearted "vorbis" Cocoa Touch Static Library, without ARC. And added all source files and header to the "vorbis" target in Build Phases tab.
In the Build Phases of OggPlayDemo Added libraries (libvorbis, OpenAl, AudioToolbox) to the Link Binary with Libraries box.
Added PA classes to project. And checked OggPlayDemo as a target. To avoid problems with ARC, I disabled ARC compilation for this 3 PA files. (see disable ARC for single file)
Removed all cocos2d references. There were some code related to correcting position of listener depending on orientation... I commented it. I don't need this feature for just playing audio.
Copied audio file.
And finally added this code to ViewController:
- (void)viewDidLoad
{
[super viewDidLoad];
//init
[PASoundMgr sharedSoundManager];
[[[PASoundMgr sharedSoundManager] listener] setPosition:CGPointMake(0, 0)];
self.audioSource = [[PASoundMgr sharedSoundManager] addSound:#"trance-loop" withExtension:#"ogg" position:CGPointMake(0, 0) looped:YES];
// lower music track volume and play it
[self.audioSource setGain:0.5f];
}
- (IBAction)play:(id)sender {
[self.audioSource playAtListenerPosition];
}
Cricket Audio will play ogg files, among others, and works on iOS/Android/WP8.

iPhone: how to make key click sound for custom keypad?

Is there a way to programmatically invoke the keypad "click" sound? My app has a custom keypad (built out of UIButtons) and I'd like to provide some audio feedback when the user taps on the keys. I tried creating my own sounds in Garageband, but wasn't happy with any of my creations. If there isn't a standard way to invoke the key click, can anyone point me to a library of sounds that might have such a gem?
There is a really fast solution to play the default keyboard sound:
Add AudioToolbox.framework
Add the following line wherever you want the sound to play:
AudioServicesPlaySystemSound(0x450);
As of iOS 4.2, adopt the UIInputViewAudioFeedback protocol on a custom subclass of UIView. Make this view your "inputView" and then call "playInputClick" at the appropriate time.
http://developer.apple.com/library/ios/#documentation/uikit/reference/UIInputViewAudioFeedback_ProtocolReference/Reference/Reference.html
Just to save some people time. Put this in your custom view:
- (BOOL) enableInputClicksWhenVisible {
return YES;
}
To make the click do this:
[[UIDevice currentDevice] playInputClick];
No need to copy the file into your own app - you should be able to get it directly from the UIKit framework:
CFURLRef soundFileURLRef = CFBundleCopyResourceURL(
CFBundleGetBundleWithIdentifier(CFSTR("com.apple.UIKit")),
CFSTR ("Tock"),CFSTR ("aiff"),NULL);
This is what I made out of it aSquared's comment:
NSString *path = [[NSBundle bundleWithIdentifier:#"com.apple.UIKit"] pathForResource:#"Tock" ofType:#"aiff"];
SystemSoundID soundID;
AudioServicesCreateSystemSoundID((CFURLRef)[NSURL fileURLWithPath:path], &soundID);
AudioServicesPlaySystemSound(soundID);
AudioServicesDisposeSystemSoundID(soundID);
The simplest way I've found is to extract Tock.aiff (the keyboard sound) from the iPhone Simulator and package it with your app, then play it using AudioServicesPlaySystemSound() at the appropriate time. On my machine, simply typing Tock.aiff into Spotlight turns up the file, but if you have to go looking for it, it's in the simulator version of UIKit.framework.
Using 0x450 as the SystemSoundID works for me (and at the correct volume - just playing the built-in Tock.aiff was too loud). No idea how portable that is - this is on an iPod Touch 3rd gen.
Still doesn't respect the preference for tick on/off.
Here's what I did:
Locate 'Tock.aiff' in: /Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator4.2.sdk/System/Library/Frameworks/UIKit.framework
Drag it into your Resources folder in xCode, ticking 'Copy items into destination group's folder'
Import AVFoundation.framework into the Frameworks folder in xCode
Import AVFoundation at the top of your class:
#import <AVFoundation/AVAudioPlayer.h>
Use the following function:
- (void)PlayClick {
NSURL* musicFile = [NSURL fileURLWithPath:[[NSBundle mainBundle]
pathForResource:#"Tock"
ofType:#"aiff"]];
AVAudioPlayer *click = [[AVAudioPlayer alloc] initWithContentsOfURL:musicFile error:nil];
[click setVolume:0.15f];
[click play];
}
That's it!
From what I can tell, the click sound isn't available to apps. I haven't seen anything in audio session services that is relevant. AudioServicesPlaySystemSound() looks promising, but there doesn't appear to be any system sound ID for the click sound (a closer look at the headers may turn up something). You could always loop over a call to AudioServicesPlaySystemSound(i) and see if anything plays. The iPhone software restore images probably have the sound, but it's probably not licensed for general use. Jailbreaking an iPhone to get at the tasty click sound doesn't need to be mentioned.
For (creative commons) sounds, check out the Freesound Project.
For the future, perhaps request that Apple expose system sounds other than the alert sound for use with AudioServicesPlaySystemSound().
Maybe a bit late ...
But in MrMage last post, if you do AudioServicesDisposeSystemSoundID(soundID); straight after AudioServicesPlaySystemSound(soundID);
then you won't hear a thing as you're discarding the system sound right after creating it.
You have to let it finish playing first.. Only call AudioServicesDisposeSystemSoundID to cancel the sound before it finishes
You do not have to dispose of the sound object right away.
Keep a pointer to that sound object in a property, and dispose of it only when you are about to play another sound before re-creating it.
And of course finally dispose of the SystemSoundID object in dealloc.

Multiple audio sounds in iPhone app?

I've gotten to play a single sound in the iPhone app I've started, but I now desire to play multiple sounds based on a button. To create a separate set of .m and .h files for each audio sounds, and then including them all, doesn't seem the most efficient way to tackle this in terms of coding...then again, I'm just starting out with Cocoa and only just completed my first app ever.
Any help is appreciated. The key here is multiple sounds, each triggered by its own button or image. Thanks.
If the files are MP3 or AAC format, then you can only play one at a time. This is a limitation of core audio on the iPhone.
In terms of playing multiple sounds at once, that's easy, just create a new player instance for every one that you want to play (and remember to release them when you're done)
NSString *path = [[NSBundle mainBundle] pathForResource:#"dream" ofType:#"m4a"];
AVAudioPlayer* theAudio=[[AVAudioPlayer alloc] initWithContentsOfURL:[NSURL fileURLWithPath:path] error:NULL];
theAudio.delegate = self;
[theAudio play];
To convert an MP3 into something like IMA4 (which you can play more than one at once) you would run the following (in terminal, in leopard):
/usr/bin/afconvert -f caff -d ima4 sound.mp3 sound.caf
The above code is firmware 2.2 only, but you can do the same with the AudioQueue files if you want to support older firmwares (it's just a lot more complex, so I haven't listed the code here).
If you have access to the iPhone developer network, then there are a bunch of code samples that show you how to play audio.
All you need to do is make one class that has a function called
-(void)Play:(NSString*)sSoundFile {
// play sound file here
}
I don't have any direct experience with iPhone development, but in theory could you create a single large sound file with all your sounds in it? Each sound could be separated by just enough silence to be individually accessed by a time index. Of course, the downside is that you'd have to load the entire file into memory, unless you could figure out a way to load chunks in a random-access fashion...
#rustyshelf - does this work in the simulator? I'm using that code, and using #import but neither audioPlayerDidFinishPlaying nor audioPlayerDecodeErrorDidOccur ever get called. Very annoying to try to debug.
http://www.icodeblog.com/2009/05/04/iphone-game-programming-tutorial-part-4-basic-game-audio/
in this example in ios5 you have to put
CFURLRef soundurl=(__bridge CFURLRef)[NSURL fileURLWithPath:objstring];
in place of
CFURLRef soundurl=(CFURLRef)[NSURL fileURLWithPath:objstring];
Hardik Mamtora