Make AVFoundation not stop iPod music - iphone

Im using the AVFoundation framework to play sound files. The problem im having is that its stopping music from playing when the audio file gets used, im not saying play both files continuously, but play the sound file, then pick up the ipod music right where it left off. Is there any way i can use AVFoundation is this kind of way? or is there a better framework for it?
Here is what my code looks like:
click = [NSURL fileURLWithPath:[NSString stringWithFormat:#"#/Click.WAV", [[NSBundle mainBundle] resourcePath]]];
audioPlayer = [[AVAudioPlayer alloc]initWithContentsOfURL:click error:nil];
audioPlayer.numberOfLoops = 1;
[click release];
[audioPlayer play];
This code works completely fine, i had to type it out so ignore any problems that there might be with it.
Thanks,
Jacob

You can use the AVAudioSession class to change the audio "category" of your app: thus you can allow it to play on top of the iPod music. Use the -setCategory:error: method, and you will probably want to use AVAudioSessionCategoryAmbient. More info can be found in the Audio Session Programming Guide.

Related

iOS record video and play MP3 at the same time

I need to record video from the iPhone camera, and play an MP3 file at the same time.
I started with AVCam sample code, which I'm sure you all have. It works great for recording video.
However, I then added the following code to play an MP3. This MP3-playing code works in a different app of mine, but when I insert it into this sample code the MP3 not only does not play, the AVCamCaptureManager's recordingDidFinishToOutputFileURL never gets called, so the video never gets saved out.
It's like the audio playing code conflicts with the video capture code. Any ideas?
Here's the audio playing code I put into AVCam:
AVAudioPlayer *audioPlayer = nil;
NSURL *url = [NSURL fileURLWithPath:[NSString stringWithFormat:#"%#/soundeffect.mp3", [[NSBundle mainBundle] resourcePath]]];
audioPlayer = [[AVAudioPlayer alloc] initWithContentsOfURL:url error:&error];
[audioPlayer setVolume:1.0];
[audioPlayer prepareToPlay];
[m_audioPlayer play];
Pretty simple code here. Not sure why this audio playing code causes recordingDidFinishToOutputFileURL to never get called...
Thanks for any ideas.
I figured it out: I just had to remove some code within AVCam that allocated AVCaptureDeviceInput - audioInput. That was unnecessary and conflicted with my audio playback code.

Couldn't play system sound after switching to iOS 5

This is how I played a beep sound effect in iOS 4:
SystemSoundId beepOnSoundId;
CFURLRef soundUrl = CFBundleCopyResourceURL(
CFBundleGetMainBundle(),
CFSTR("beep"),
CFSTR("wav"),
NULL
);
// soundUrl logged:
// file://localhost/var/mobile/Applications/ ... beep.wav
AudioServicesCreateSystemSoundID(soundUrl, &beepOnSoundId);
// beepOnSoundId logged: 4097
AudioServicesPlaySystemSound(beepOnSoundId);
It stopped working, when I upgraded my device to iOS 5. I hear nothing. I logged out all the variables and none were nil or 0.
How has the API changed in iOS 5 that breaks my sound playing code?
Update
The problem may be because I have an AVCaptureSession running while I play the sound. iOS 5 somehow doesn't let you do this anymore. I need to play a beep sound while I am recording something from the camera.
This bug report could be related to your question, if you have an AVCaptureSession running.
Under iOS 5, when using an AudioServicesPlaySystemSound call, it will
not work when there is an active AVCaptureSession with an audio device
active.
One problem could be that in ios 5 when you call AudioServicesPlaySystemSound, it stop working if there is an active AVCaptureSession with an audio device active.
Also check the names of imports in your files, make sure the audiotoolbox import is in all your viewcontrollers.
I also went to a guide and got this for you :) I'll leave the website's name at the bottom
Step 1: Import the AudioToolbox Framework
Begin by importing the Audio Toolbox framework into your application in order to make the System Sound Services available to your code. To do so, select the “PhoneAppSkin” project in the Project Navigator pane in Xcode, then select “PhoneAppSkin” under “TARGETS”, and finally select the “Build Phases” tab. After doing so, your screen should look something like this:
Next, click the “Link Binary With Libraries” drop down, and click the “+” symbol to add a new framework to our project’s linking phase.
Finally, find the “AudioToolbox” framework in the popup window, and then click “Add”.
Next, open up the PhoneViewController.h file and add the line necessary to actually import the Audio Toolbox framework into your class:
#import <UIKit/UIKit.h>
#import <AudioToolbox/AudioToolbox.h>
The Audio Toolbox functions should now work
Website I got the images from: http://mobile.tutsplus.com/tutorials/iphone/ios-sdk_playing-systemsoundid/
I have almost the same code and it works for me in iOS5 with a video and an audio media sessions on. If you have all the code in a function to play the sound the problem may be that the SystemSoundID object gets deallocated before the sound can be played, or the problem may be with the URL. But I guess it is the first one.
See, the following code works:
The SystemSoundID declaration is in the header of the object and the object lives long enough to play the sound.
SystemSoundID soundID;
The AudioServicesCreateSystemSoundID is in the object initialization.
AudioServicesCreateSystemSoundID((CFURLRef)[NSURL fileURLWithPath:[[NSBundle mainBundle]
pathForResource: #"sound" ofType:#"wav"]], &soundID);
Then you can use AudioServicesPlaySystemSound wherever you want inside the object.
AudioServicesPlaySystemSound(soundID);
Try putting this pieces codes in the appropriate places and you should hear the sound.
In my Constructor:
[[AVAudioSession sharedInstance] setCategory: AVAudioSessionCategoryPlayback error: nil];
UInt32 doSetProperty = 1;
AudioSessionSetProperty (kAudioSessionProperty_OverrideCategoryMixWithOthers, sizeof(doSetProperty), &doSetProperty);
[[AVAudioSession sharedInstance] setActive: YES error: nil];
NSURL* musicFile = [NSURL fileURLWithPath:[[NSBundle mainBundle]
pathForResource:#"video-sent"
ofType:#"caf"]];
self.sentSound = [[AVAudioPlayer alloc] initWithContentsOfURL:musicFile error:nil];
[self.sentSound prepareToPlay];
The function playSentSound
- (void)playSentSound
{
DLog(#"PLay Sound %#", self.sentSound);
[self.sentSound play];
}
then later in the code i just call it
[self playSentSound];
The key here are the first 4 lines ... ;-)

Couldn't put a song into an app

Have already tried that out and failed
I put a .wav file into my app and it was fine. So I tried to put a .wav song file into the app. When runs, there's no sound coming out. ( the song is converted from .mp3 using iTunes)
Any ideas how can I fix this? Thanks in advance
one possible reason the sound file is too large. You have different kinds of audio player in iOS some of them can only play files that are really short (something like 1-3 sec). To fix that you have to choose another player like CoreAudio.
The second possible failure is the simulator. The simulator is not always doing the same, the device do. Try running on real device and check if it's working.
// EDIT: sample code:
NSString *soundFilePath = [[NSBundle mainBundle] pathForResource:#"mySound" ofType:#"mp3"];
NSURL *soundFileURL = [NSURL URLForString:soundFilePath];
AVAudioPlayer *player = [[AVAudioPlayer alloc]initWithContentsOfURL:soundFileURL];
[player play];
[player pause];

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.