I am using the following code: https://stackoverflow.com/a/14063081/1011125.
Now I need to enable the sound which is played if a picture is taken.
Can anyone help me?
There's two ways to do that:
1) Using AVAudioPlayer
In your myPic.m adding:
//at the top
#import <AudioToolbox/AudioToolbox.h>
#import <MediaPlayer/MediaPlayer.h>
#implementation myPic {
AVAudioPlayer *mySound;
}
//then use this function where ever you want to play sound
NSString *soundFilePath = [[NSBundle mainBundle] pathForResource: #"mySound" ofType: #"mp3"]; //wav, aiff, ogg, ext
NSURL *fileURL = [[NSURL alloc] initFileURLWithPath: soundFilePath];
loopUno = [[AVAudioPlayer alloc] initWithContentsOfURL: fileURL error: nil];
loopUno.numberOfLoops = 0; // here loop setup infinite is -1
[mySound play];
2) i prefer, have no loop but is more stable is SystemSoundID soundID
//at the top
#import <AudioToolbox/AudioToolbox.h>
#import <MediaPlayer/MediaPlayer.h>
#implementation myPic {
SystemSoundID soundID;
}
//then use this function where ever you want to play sound
AudioServicesDisposeSystemSoundID(soundID);
CFBundleRef mainBundle = CFBundleGetMainBundle();
CFURLRef soundFileURLRef;
soundFileURLRef = CFBundleCopyResourceURL(mainBundle, (CFStringRef) #"mySound" ,CFSTR ("mp3") , NULL); //wav, aiff, ogg, ext
AudioServicesCreateSystemSoundID(soundFileURLRef, &soundID);
AudioServicesPlaySystemSound(soundID);
Override Speaker:
- (void)viewDidLoad {
[super viewDidLoad];
AVAudioSession* session = [AVAudioSession sharedInstance];
BOOL success;
NSError* error;
success = [session setCategory:AVAudioSessionCategoryPlayAndRecord error:&error];
success = [session overrideOutputAudioPort:AVAudioSessionPortOverrideSpeaker error:&error];
success = [session setActive:YES error:&error];
}
or if you use more audio in you app add the function inside you AppDelegate.m under application didFinishLaunchingWithOptions: and import your delegate where you need
Hope this help you ;)
Place this code for shutter sound,
AudioServicesPlaySystemSound(1108);
Note: http://iphonedevwiki.net/index.php/AudioServices
Related
I have a series of sound files ranging from 0.3s to 3.0s.
When trying to play with AVAudioPlayer, I get nothing, unless I add a sleep(4) call after to ensure the sound can play. Really weird.
Apart from that, no errors with the error param that gets passed in, and the [player play] returns YES every time. The delegate methods are not called, though, oddly enough.
Here's my code.
(.m file)
#interface MyClass ()
#property (nonatomic, strong) AVAudioPlayer *soundPlayer;
#end
#implementation SLInspireKit
//view did load here
- (void)playRandomSound {
AVAudioSession *session = [AVAudioSession sharedInstance];
[session setCategory:AVAudioSessionCategoryPlayback error:nil];
NSError *error;
NSString *musicFileName = [NSString stringWithFormat:#"my-sound-%d.aiff", arc4random_uniform(8)];
NSString *path = [NSString stringWithFormat:#"%#/%#", [[NSBundle mainBundle] resourcePath], musicFileName];
NSURL *soundUrl = [NSURL fileURLWithPath:path];
self.soundPlayer = [[AVAudioPlayer alloc] initWithContentsOfURL:soundUrl error:&error];
self.soundPlayer.delegate = self;
[self.soundPlayer setVolume:1.0];
[self.soundPlayer prepareToPlay];
if ([self.soundPlayer play]){
NSLog(#"Played fine");
} else {
NSLog(#"Did not play fine");
}
sleep(1); //uncomment this out, and nothing. Set to 1, first second of each sound, 2, 2 seconds and so on.
}
Any ideas? I don't think it's an ARC thing, but it could be :/ I have to initiate each time because the sound changes each time.
Quick summary of the comments:
Turns out the sleep(n) was needed since the entire class containing the AVAudioPlayer was deallocated.
Retaining the class fixes the issue.
Cheers!
So in my file I have the following code with the intention that a music file plays in the background :
-(void) BackGroundMusic {
NSString *soundPath = [[NSBundle mainBundle]pathForResource:#"LostInTheSea" ofType:#"mp3"];
SystemSoundID soundID;
AudioServicesCreateSystemSoundID((__bridge CFURLRef)[NSURL fileURLWithPath: soundPath], &soundID);
AudioServicesPlaySystemSound(soundID);
}
And then in the view did load section I have :
[self BackGroundMusic];
I have all the toolboxes added such as AVFoundation and AudioToolbox but i can not hear any audio playing . Please help !
You should not be using system sound to play mp3 files as user523234 explains.
Use AVAudioPlayer instead. Here's an example that will loop infinitely:
#import "AVFoundation/AVAudioPlayer.h"
#import "AVFoundation/AVAudioSession.h"
-(void)playbgMusic {
AVAudioPlayer *soundbgMusic;
NSString *soundPath;
soundPath= [[NSBundle mainBundle] pathForResource:#"bgMusic" ofType:#"mp3"];
soundbgMusic = [[AVAudioPlayer alloc] initWithContentsOfURL:[NSURL fileURLWithPath:soundPath] error:NULL];
soundbgMusic.volume = 1.0;
soundbgMusic.numberOfLoops = -1;
[soundbgMusic prepareToPlay];
soundbgMusic.currentTime = 0.0;
[soundbgMusic play];
}
According to the document for AudioServicesPlaySystemSound:
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
I'm struggling to follow Apple's documentation regarding playing back a small .wav file using the AVAudioPlayer class. I'm also not sure what toolboxes I need for basic audio playback. So far I have imported:
AVFoundation.framework
CoreAudio.framework
AudioToolbox.framework
Here is my code .h and .m:
#import <UIKit/UIKit.h>
#import <AVFoundation/AVFoundation.h>
#interface ViewController : UIViewController <AVAudioPlayerDelegate>
- (IBAction)playAudio:(id)sender;
#end
#import "ViewController.h"
#interface ViewController ()
#end
#implementation ViewController
- (void)viewDidLoad
{
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
}
- (IBAction)playAudio:(id)sender {
NSLog(#"Button was Pressed");
NSString *filePath = [[NSBundle mainBundle] pathForResource:#"XF_Loop_028" ofType:#"wav"];
NSURL *fileURL = [[NSURL alloc] initFileURLWithPath:filePath];
// create new audio player
AVAudioPlayer *myPlayer = [[AVAudioPlayer alloc]initWithContentsOfURL:fileURL error:nil];
[myPlayer play];
}
#end
I don't seem to have any errors. However, I am not getting any audio.
You're having an ARC issue here. myPlayer is being cleaned up when it's out of scope. Create a strong property, assign the AVAudioPlayer and you're probably all set!
#property(nonatomic, strong) AVAudioPlayer *myPlayer;
...
// create new audio player
self.myPlayer = [[AVAudioPlayer alloc]initWithContentsOfURL:fileURL error:nil];
[self.myPlayer play];
Is the filePath coming back with a valid value? Is the fileURL coming back with a valid value? Also, you should use the error parameter of AVAudioPlayer initWithContentsOfURL. If you use it it will likely tell you EXACTLY what the problem is.
Make sure you check for errors and non-valid values in your code. Checking for nil filepath and fileURL is the first step. Checking the error parameter is next.
Hope this helps.
What I do is create an entire miniature class just for this purpose. That way I have an object that I can retain and which itself retains the audio player.
- (void) play: (NSString*) path {
NSURL *fileURL = [[NSURL alloc] initFileURLWithPath: path];
NSError* err = nil;
AVAudioPlayer *newPlayer =
[[AVAudioPlayer alloc] initWithContentsOfURL: fileURL error: &err];
// error-checking omitted
self.player = newPlayer; // retain policy
[self.player prepareToPlay];
[self.player setDelegate: self];
[self.player play];
}
I have would like to play audio on the startup of my app, but, first of all, the audio doesn't play! No matter how i code it. And secondly I would love to loop it if i can.
#implementation ViewController
-(void)awakeFromNib
{
SystemSoundID soundID;
NSString *soundFile1 = [[NSBundle mainBundle] pathForResource:#"ScaryMusic" ofType:#"mp3"];
AudioServicesCreateSystemSoundID((__bridge CFURLRef) [NSURL fileURLWithPath:soundFile1], &soundID);
AudioServicesPlaySystemSound(soundID);
NSLog(#"Sound Played");
}
Try this instead:
#import <AVFoundation/AVFoundation.h>
AVAudioPlayer *player;
NSURL *soundFileURL = [[NSBundle mainBundle] URLForResource:#"ScaryMusic" withExtension:#"mp3"];
if (soundFileURL != nil)
{
player = [[AVAudioPlayer alloc] initWithContentsOfURL:soundFileURL error:nil];
player.numberOfLoops = -1; //infinite
}
[player play];
This is better for mp3's and such. SystemSound is mostly reserved for short .wav type sounds.
If you look in the docs you'll find that mp3 is not among the formats supported by AudioToolbox
I uploaded a file audio.wav into my supporting files folder.
This is my PlayAudio.h
#import <UIKit/UIKit.h>
#import <AudioToolbox/AudioToolbox.h>
#import <AVFoundation/AVFoundation.h>
#interface PlayAudio : UIViewController {
}
-(IBAction) PlayIt;
#end
This is my PlayAudio.m after the implementation command
- (IBAction) PlayIt; {
CFBundleRef mainBundle = CFBundleGetMainBundle();
CFURLRef soundFileURLRef;
soundFileURLRef = CFBundleCopyResourceURL(mainBundle, (CFStringRef) #"audio", CFSTR ("wav"), NULL);
UInt32 soundID;
AudioServicesCreateSystemSoundID(soundFileURLRef, &soundID);
AudioServicesPlaySystemSound(soundID);
}
I then ctrl-clicked from the play button to the First Responder in my view controller and selected PlayIt. I see it's associated with Touch Up Inside.
For some reason I can click the button, but nothing plays. I'm doing this in Storyboard.
You can use NSURL to get the path of your wav file and cast it to CFURLRef, check the following code:
SystemSoundID soundID;
NSURL *soundPath = [NSURL fileURLWithPath:[[NSBundle mainBundle] pathForResource:#"audio" ofType:#"wav"]];
if (AudioServicesCreateSystemSoundID ((CFURLRef)soundPath, &soundID) != kAudioServicesNoError) {
AudioServicesPlayAlertSound(soundID);
}
Note, that if mute button on iphone is enable AudioServicesCreateSystemSoundID function will fail(Vibration can be used in this case:soundID = kSystemSoundID_Vibrate;). If you want to play sound disregarding the mute switch, use AVAudioPlayer api.