Here is the code:
-(void)stop
{
NSLog(#"Disposing Sounds");
AudioServicesDisposeSystemSoundID (soundID);
//AudioServicesRemoveSystemSoundCompletion (soundID);
}
static void completionCallback (SystemSoundID mySSID, void* myself) {
NSLog(#"completion Callback");
}
- (void) playall: (id) sender {
[self stop];
AudioServicesAddSystemSoundCompletion (soundID,NULL,NULL,
completionCallback,
(void*) self);
OSStatus err = kAudioServicesNoError;
NSString *aiffPath = [[NSBundle mainBundle] pathForResource:#"slide1" ofType:#"m4a"];
NSURL *aiffURL = [NSURL fileURLWithPath:aiffPath];
err = AudioServicesCreateSystemSoundID((CFURLRef) aiffURL, &soundID);
AudioServicesPlaySystemSound (soundID);
NSLog(#"Done Playing");
}
Output:
Disposing Sounds
Done Playing
In actual no sound gets play at all and completion call back isn't called as well. Any idea what could be wrong here?
I want to stop any previous sound before playing current.
AFAIK, the only supported files are .caf, .aif, or .wav:
To play your own sounds, add the sound
file to your application bundle; the
sound file must adhere to the
following requirements:
Must be .caf, .aif, or .wav files.
The audio data in the file must be in PCM or IMA/ADPCM (IMA4) format.
The file's audio duration must be less than 30 seconds.
Audio & Video Coding How-To's
What does err contain? From that you should be able to infer the problem.
You can use AudioToolBox framework for this:
CFBundleRef mainbundle = CFBundleGetMainBundle();
CFURLRef soundFileURLRef = CFBundleCopyResourceURL(mainbundle, CFSTR("tap"), CFSTR("aif"), NULL);
AudioServicesCreateSystemSoundID(soundFileURLRef, &soundFileObject);
AudioServicesPlaySystemSound(kSystemSoundID_Vibrate);
AudioServicesPlaySystemSound(1100);
Related
I created this method to easily play sounds in an XCode iPhone application.
void playSound(NSString* myString) {
CFBundleRef mainBundle = CFBundleGetMainBundle();
NSString *string = myString;
CFURLRef soundFileURLRef;
soundFileURLRef = CFBundleCopyResourceURL(mainBundle, (__bridge CFStringRef) string, CFSTR ("wav"), NULL);
UInt32 soundID;
AudioServicesCreateSystemSoundID(soundFileURLRef, &soundID);
AudioServicesPlaySystemSound(soundID);
}
The problem with this is, I don't know how to later stop the sound or to make the sound play on a loop forever until it is stopped. How would I go about doing this? Could I possibly make the method return the sound, and then put that in a variable to later be modified?
I'm afraid i dont know how to stop it, but try this for looping:
soundFile = [NSURL fileURLWithPath: [[NSBundle mainBundle] pathForResource:#"AudioName" ofType:#"wav"]];
sound = [[AVAudioPlayer alloc] initWithContentsOfURL:soundFile error:nil];
sound.numberOfLoops = -1; //infinite
[sound play];
From documentation: "The interface does not provide level, positioning, looping, or timing control, and does not support simultaneous playback...".
http://developer.apple.com/library/ios/#documentation/AudioToolbox/Reference/SystemSoundServicesReference/Reference/reference
So for sound playback it is better use AVFoundation classes.
System Sound Services usually is used to play short sounds/alerts/etc and pausing/stopping probably should be avoided. If this is really needed you could try AudioServicesDisposeSystemSoundID(systemSoundID) to stop the sound.
As for looping you could create recursive function to loop the sound using AudioServicesPlaySystemSoundWithCompletion.
Example (swift 3):
func playSystemSound(systemSoundID: SystemSoundID, count: Int){
AudioServicesPlaySystemSoundWithCompletion(systemSoundID) {
if count > 0 {
self.playSystemSound(systemSoundID: systemSoundID, count: count - 1)
}
}
}
So in your example you would just replace AudioServicesPlaySystemSound(soundID); with playSystemSound(systemSoundID: soundID, count: numOfPlays)
In case if you want to decide to play a sound based on a bool variable,
private func playSound() {
if isStarted {
AudioServicesPlaySystemSoundWithCompletion(kSystemSoundID_Vibrate, {
if self.isStarted {
self.playSound()
}
})
}
}
I want to play sound in my application for that I am using .mp3 file type. It is working fine in Simulator but when I am lunching it to my device it is not working and not producing any sound can any one help me why it is not working on device or which file format is better to play audio file in iPhone and iPad?
NSURL *tapSound = [[NSBundle mainBundle] URLForResource: [NSString stringWithFormat:#"%#",SoundFileName] withExtension: #""];
// Store the URL as a CFURLRef instance
self.soundFileURLRef = (CFURLRef) [tapSound retain];
// Create a system sound object representing the sound file.
AudioServicesCreateSystemSoundID (
soundFileURLRef,
&soundFileObject
);
AudioServicesPlaySystemSound (soundFileObject);
Above is mine code to play sound
Thank you.
The system sound IDs won't play if the device is muted, so this is possibly the cause. (They're only really for the purpose of user interface effects such as alerts, etc. as per the official documentation.)
As such, I'd be tempted to use the AVAudioPlayer style approach. As a sample (no pun intended) implementation:
// *** In your interface... ***
#import <AVFoundation/AVFoundation.h>
...
AVAudioPlayer *testAudioPlayer;
// *** Implementation... ***
// Load the audio data
NSString *soundFilePath = [[NSBundle mainBundle] pathForResource:#"sample_name" ofType:#"wav"];
NSData *sampleData = [[NSData alloc] initWithContentsOfFile:soundFilePath];
NSError *audioError = nil;
// Set up the audio player
testAudioPlayer = [[AVAudioPlayer alloc] initWithData:sampleData error:&audioError];
[sampleData release];
if(audioError != nil) {
NSLog(#"An audio error occurred: \"%#\"", audioError);
}
else {
[testAudioPlayer setNumberOfLoops: -1];
[testAudioPlayer play];
}
// *** In your dealloc... ***
[testAudioPlayer release];
You should also remember to set the appropriate audio category. (See the AVAudioSession setCategory:error: method.)
Finally, you'll need to add the AVFoundation library to your project. To do this, alt click on your project's target in the Groups & Files column in Xcode, and select "Get Info". Then select the General tab, click the + in the bottom "Linked Libraries" pane and select "AVFoundation.framework".
I honestly would suggest using AVAudioPlayer instead of this, but you could try using this alternate code instead. In your example it looks like you forgot to include the extension, which might be the problem also. The simulator is more lenient on naming, so if you forgot the extension it might play on the simulator and not a device.
SystemSoundID soundFileObject;
CFURLRef soundFileURLRef = CFBundleCopyResourceURL (CFBundleGetMainBundle (),CFSTR ("sound"),CFSTR ("mp3"),NULL );
AudioServicesCreateSystemSoundID (soundFileURLRef,&soundFileObject );
AudioServicesPlaySystemSound (soundFileObject);
I have a button on a UIImagePicker overly , and I want it to make some sound when clicked.
To do so, I have in my project resources a sound in m4a and mp3 formats (for test purpose).
I try to play the sound by many ways, trying alternatively with m4a and mp3 formats, but nothing goes out of the iPhone (not the simulator).
The Frameworks are include in the project.
Here is my sample code :
#import <AudioToolBox/AudioToolbox.h>
#import <AVFoundation/AVAudioPlayer.h>
- (IBAction) click:(id)sender {
// Try
/*
SystemSoundID train;
AudioServicesCreateSystemSoundID(CFBundleCopyResourceURL(CFBundleGetMainBundle(), CFSTR("TheSound"), CFSTR("mp3"), NULL), &train);
AudioServicesPlaySystemSound(train);
*/
// Try
/*
NSError *error;
AVAudioPlayer *audioPlayer = [[AVAudioPlayer alloc] initWithContentsOfURL:[[NSBundle mainBundle] URLForResource: #"TheSound" withExtension: #"mp3"] error:&error];
[audioPlayer play];
[audioPlayer release];
*/
// Try (works)
//AudioServicesPlayAlertSound(kSystemSoundID_Vibrate);
// Try
/*
SystemSoundID soundID;
NSURL *filePath = [NSURL fileURLWithPath:[[NSBundle mainBundle] pathForResource:#"TheSound" ofType:#"mp3"] isDirectory:NO];
AudioServicesCreateSystemSoundID((CFURLRef)filePath, &soundID);
AudioServicesPlaySystemSound(soundID);
*/
NSLog(#"Clicked");
}
Could you tell me what is going wrong ?
You can't use an MP3 with Audio Services. It must be a WAV file of a certain subtype. As for AVAudioPlayer, it supports MP3 files but when AVAudioPlayer is deallocated it stops playback, and since you do so immediately after sending -play (by sending -release to balance the +alloc), you never hear anything.
So either convert the file to WAV, or hang onto your AVAudioPlayer long enough for it to play. :)
we are trying to use remoteio for audio recording in conjunction
with the AudioServicesPlaySystemSound function for audio playback. the problem is that whenever remoteio is running the playback volume drops
significantly. it seems like if some final mixing takes place behind the scene but we do not no how to change this behavior.
the implementation of the remoteio is based on the fallowing blog
http://atastypixel.com/blog/using-remoteio-audio-unit/
for audio playback we just use code like this one
NSString *sndPath = [[NSBundle mainBundle] pathForResource:#"test" ofType:#"wav" inDirectory:#"/"];
CFURLRef sndURL = (CFURLRef)[[NSURL alloc] initFileURLWithPath:sndPath];
SystemSoundID soundID;
int e = AudioServicesCreateSystemSoundID(sndURL, &soundID);
if (e) {
NSLog(#"couldn't create sound");
exit(0);
}
AudioServicesPlaySystemSound(soundID);
thanks a lot for any help
You may have to disable the voice processing AGC.
i have buttons on my application and have a short sound effect , when user taps on buttons , short sound plays but if someone listen to the music , the music will stop ! how can i handle this ? to play music and my effect ,i use AudioToolbox framework .
i read apple documentation doesn't work with AVFoundation.framework ! for some reasons i can't change my code ! is there any way for systemSoundID ?
-(void)soundType{
NSString *path = [NSString stringWithFormat:#"%#%#",[[NSBundle mainBundle] resourcePath], #"/type.wav"];
SystemSoundID soundID;
NSURL *filePath = [NSURL fileURLWithPath:path isDirectory:NO];
AudioServicesCreateSystemSoundID((CFURLRef)filePath, &soundID);
AudioServicesPlaySystemSound(soundID);
}
Do you mean that when iPod music is playing and you run your app, the music stops? If so, you should set your audio session to ambient sound so that the iPod can continue playing. Try this:
AudioSessionInitialize(NULL, NULL, NULL, self);
UInt32 category = kAudioSessionCategory_AmbientSound;
AudioSessionSetProperty(kAudioSessionProperty_AudioCategory, sizeof(category), &category);
AudioSessionSetActive(YES);
You can try using NSSound
NSSound *snd = [[NSSound alloc] initWithContentsOfFile: fileName byReference: NO];
[snd play];