playing a sound doesn't work on iPhone - iphone

I've added a sound to my app.
In my .h i've added:
CFURLRef soundFileURL;
SystemSoundID soundFile;
in my viewDidLoad in my .m:
soundFileURL = CFBundleCopyResourceURL(
CFBundleGetMainBundle(),
CFSTR("sound"),
CFSTR("mp3"),
NULL);
AudioServicesCreateSystemSoundID(
soundFileURL,
&soundFile);
and lastly i've added a -playSound method:
-(void)playSound {
NSLog(#"playSound");
AudioServicesPlayAlertSound(soundFile); }
It works fine on the iPhone Simulator, but when I build the app on my iPhone the console says the sound was played but it wasn't.
I read that many others had this problem too but I didn't find any solutions.
What's wrong?

It could be your encoding - the audio codecs on the simulator are much different than those provided by your actual iPhone hardware. Try reencoding.
Also - you don't want to use an mp3 for a sound, you want to use a non-compressed file format (I suggest aiff from experience) because there isn't dedicated decoding hardware to support the sound decoding you're trying to do. (There is for playing music, which mp3 is recommended for)

I would recommend AVAudioPlayer in the AVFoundation framework. It has a simple asynchronous interface for sound playback on iOS.
Check out the Apple programming guide here.

I had a similar issue. It turned out I was referencing "Horn.caf" with
NSURL *hornSound = [[NSBundle mainBundle] URLForResource: #"horn"
withExtension: #"caf"];
Note the difference in case; My OS X Lion install is on a case insensitive file system.
Changing the code to the following fixed the issue.
NSURL *hornSound = [[NSBundle mainBundle] URLForResource: #"Horn"
withExtension: #"caf"];
Hope that helps others.

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.

Playing a video in ipad

I want to play a movie in my app and the video is stored in my ipad library.
Can anyone provide me the necessary guidance for it?
Get the MPMediaItem of the video you want using MPMediaQuery
Get the Asset URL like this:
NSURL *videoURL = [mediaItem valueForProperty:MPMediaItemPropertyAssetURL];
Instantiate an MPMoviePlayerViewController using videoURL as the content URL.
If the video is stored in your App's bundle then do this to get the URL:
NSURL *videoURL = [[NSBundle mainBundle] URLForResource:#"nameoffile" withExtension:#"mp4"];
See a sample of a custom view/viewController combo in Pragmatic iPad Programming. Check the source code for chapter 8 (free download from that page). They use a video provided as a file inside the project. Btw, if the file in the video appears red in XCode, you'll have to remove it and re add it, I think the project definition is a bit screwed.

Sound on simulator but not device

I'm using the following to play an m4a file:
NSString *path = [[[NSBundle mainBundle] resourcePath] stringByAppendingPathComponent: fileName];
SystemSoundID soundID;
NSURL *filePath = [NSURL fileURLWithPath:path isDirectory:NO];
AudioServicesCreateSystemSoundID((CFURLRef)filePath, &soundID);
AudioServicesPlaySystemSound(soundID);
It works fine on the simulator but I hear nothing on the device. Sounds files I'm using all stay in the bundle. Here is what filePath looks like from the device:
file://localhost/var/mobile/Applications/418945F3-3711-4B4D-BC65-0D78993C77FB/African%20Adventure.app/Switch%201.m4a
Is there an issue with the file path or any thing different I need to do for the device?
Just as a sidenote - I was having the exact same problem and spent probably close to an hour on converting files to the correct format, etc.. Yet the problem was the "mute" switch on the iPad. So even though the volume was up, and I could hear other sounds on the iPad, because the mute switch was turned on, it wasn't playing system sounds.
To add to the confusion, this app uses text-to-speech and the volume coming from the dictation was perfectly fine, it was only the sounds coming from AudioServicesPlaySystemSound() that weren't being played.
I had trouble with this too. Finally I realised it was because AudioServices can only play audio with the following constratints.
Sound files that you play using this
function must be:
- No longer than 30 seconds in duration
- In linear PCM or IMA4 (IMA/ADPCM) format
- Packaged in a .caf, .aif, or .wav file
From Apple docs: http://developer.apple.com/library/ios/#documentation/AudioToolbox/Reference/SystemSoundServicesReference/Reference/reference.html
You might want to use the AVAudioPlayer instead of AudioServices.
The following code will take an audio file (.m4a) and play the audio file 1 time. Don't forget to release "audioPlayer" when you're done with it.
NSString *urlAddress = [[NSBundle mainBundle] pathForResource:#"filename" ofType:#"m4a"];
NSURL *url = [NSURL fileURLWithPath:urlAddress];
NSError *error;
AVAudioPlayer *audioPlayer = [[AVAudioPlayer alloc] initWithContentsOfURL:url error:&error];
audioPlayer.numberOfLoops = 0;
if (audioPlayer == nil)
{
NSLog([error description]);
}
else
{
[audioPlayer play];
}
Hope this example helps you with playing audio on the actual device. It might also be a good idea to increase the device audio when the file is playing.
Note: You will need to add the AVFoundation framework to your project if you have not already done so. As well as import the header file.
#import <AVFoundation/AVFoundation.h>
Update:
From Apple's Core Audio Overview Document
Audio Session Services
Audio Session Services lets you manage audio sessions in your application—coordinating the audio behavior in your application with background applications on an iPhone or iPod touch. Audio Session Services consists of a subset of the functions, data types, and constants declared in the AudioServices.h header file in AudioToolbox.framework.
The AVAudioPlayer Class
The AVAudioPlayer class provides a simple Objective-C interface for playing sounds. If your application does not require stereo positioning or precise synchronization, and if you are not playing audio captured from a network stream, Apple recommends that you use this class for playback. This class is declared in the AVAudioPlayer.h header file in AVFoundation.framework.
Start by error-checking your returns. Is filePath nil? Do either of the AudioServices functions return an error? The most likely cause is case-sensitivity. The iPhone filesystem is case sensitive while the Mac is not. But the first step in debugging is to look at the errors the system is providing.
The simulator uses regular QuickTime for playback, so it's easy to have media assets which work in the sim, but fail on the device due to missing / unsupported codecs. The test is if you can play the file at all on the device, eg through Safari or the iPod app.

What's the SIMPLEST way to play a sound clip in an iPhone app?

I want to be able to play a sound clip in an iPhone OS app. I've seen info on both NSSound as well as AVFoundation as being means for getting sound clips played on an iPhone OS device, but I'm still not clear on the subject and could use some help. No need to spell it out for me step-by-step in actual code, but if someone could give me a hint as to the general direction (i.e. which classes I should be focusing on) in which I should start moving I'll fill in the blanks myself. So, what's the SIMPLEST way to play a sound clip in an iPhone app?
Apple has an article on this subject, see: this link
AVAudioPlayer is the simplest way to play sounds of any length, looping or not, however it requires iPhone OS 2.2 or higher. A simple example:
NSString *soundFilePath =
[[NSBundle mainBundle] pathForResource: #"sound"
ofType: #"wav"];
NSURL *fileURL = [[NSURL alloc] initFileURLWithPath: soundFilePath];
AVAudioPlayer *newPlayer =
[[AVAudioPlayer alloc] initWithContentsOfURL: fileURL
error: nil];
[fileURL release];
[newPlayer play];
[newPlayer release];
It will play virtually any file format (aiff,wav,mp3,aac) Keep in mind that you can only play one mp3/aac file at a time.
Here's the simplest way I know of:
Convert your sound file to caf (use afconvert commandline tool) and add to your project.
caf stands for Core Audio Format (I think...)
Look for SoundEffect.h and .m in Apple's sample code. I believe both Metronome and BubbleLevel have it.
Copy to your project
Write code like below:
SoundEffect *SimpleSound = [[SoundEffect alloc] initWithContentsOfFile:[mainBundle pathForResource:#"soundfile" ofType:#"caf"]];
[SimpleSound play];
[SimpleSound release];
Study SoundEffect.m to get an idea of simple sound handling.

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