I've been looking for a while how to play sound on the iphone, and I think it's something along the lines of:
[[NSSound soundNamed:#"cat.mp3"] play];
But the NSSound is on the AppKit ... any suggestions ? I know there is a really simple answer to this, but today my searches are not rendering any result ...
the new AVFoundation class is the easiest way to play sound on the iPhone, though it is for firmware 2.2 only:
AVAudioPlayer *audioPlayer = [[AVAudioPlayer alloc] initWithContentsOfURL:[NSURL fileURLWithPath:path] error:NULL];
[audioPlayer play];
you just need this import in the class that uses it:
#import <AVFoundation/AVAudioPlayer.h>
Audio Toolbox system sounds are great for short async playback.
// Initialize
CFBundleRef mainBundle;
mainBundle = CFBundleGetMainBundle ();
// Init each sound
CFURLRef tapURL;
SystemSoundID tapSound;
tapURL = CFBundleCopyResourceURL(mainBundle, CFSTR("tap"), CFSTR("aif"), NULL);
AudioServicesCreateSystemSoundID(tapURL, &tapSound);
// Play the sound async
AudioServicesPlaySystemSound(tapSound);
I haven't gotten MP3s to work with AudioServicesPlaySystemSound. But it plays AIF files perfectly.
Related
This question already has answers here:
iPhone - Is it possible to override silent mode or have a recursive alert sound with push notification? [closed]
(3 answers)
Closed 4 years ago.
I want to make an application which creates sound, music, or system sound when an iPhone is in silent mode. Is it possible to play any type of sound whether music or system tones when it is silent mode?
It's not advisable, but who am I to say you can't do it. You may have a good reason to be playing sound.
If you are using Audio Sessions, then include <AVFoundation/AVFoundation.h> at the start of your file and
[[AVAudioSession sharedInstance]
setCategory: AVAudioSessionCategoryPlayback
error: nil];
should do the trick. Note if you play music or sounds, then iPod playback will be paused.
Once this has been done, probably somewhere in the initialization of one of your classes that plays the sounds, you can instantiate sounds like this:
// probably an instance variable: AVAudioPlayer *player;
NSString *path = [[NSBundle mainBundle] pathForResource...];
NSURL *url = [NSURL fileURLWithPath:path];
player = [[AVAudioPlayer alloc] initWithContentsOfURL:url];
When that's done, you can play with it any time you want with:
[player play]; // Play the sound
[player pause]; // Pause the sound halfway through playing
player.currentTime += 10 // skip forward 10 seconds
player.duration // Get the duration
And other nice stuff. Look up the AVAudioPlayer Class reference.
And for Swift 2, 3, 4.2
do {
try AVAudioSession.sharedInstance().setCategory(AVAudioSessionCategoryPlayback)
try AVAudioSession.sharedInstance().setActive(true)
} catch {
print(error)
}
Yes you can play sound when the phone is set to vibrate.
Simply use the AVAudioPlayer class.
By default, playing an Audio Session
sound will ~not~ respect the setting
of the mute switch on the iPhone. In
other words, if you make a call to
play a sound and the silent (hardware)
switch on the iPhone is set to silent,
you’ll still hear the sound.
This is what you want. So now you know that playing an Audio Session when your phone is in silent mode will still play the sound you just need to know how to create an audio session to play the sound, like so:
taken from this website: http://iosdevelopertips.com/audio/playing-short-sounds-audio-session-services.html
SystemSoundID soundID;
NSString *path = [[NSBundle mainBundle]
pathForResource:#"RapidFire" ofType:#"wav"];
AudioServicesCreateSystemSoundID((CFURLRef)[NSURL fileURLWithPath:path],&soundID);
AudioServicesPlaySystemSound (soundID);
For this to work, you will need to import header file, and also add the AudioToolbox.framework to your project.
And that's it.
So from this answer you now know that you can play sound while the phone is on vibrate.
You don't need extra or special code to allow you to do this functionality as it already does that by default.
Pk
Works on iOS 6 and above
NSError *setCategoryErr = nil;
NSError *activationErr = nil;
[[AVAudioSession sharedInstance] setCategory:AVAudioSessionCategoryPlayback error:&setCategoryErr];
[[AVAudioSession sharedInstance] setActive:YES error:&activationErr];
Just put this in your viewDidLoad:
UInt32 sessionCategory = kAudioSessionCategory_MediaPlayback;
AudioSessionSetProperty (kAudioSessionProperty_AudioCategory,
sizeof(sessionCategory), &sessionCategory);
For playing a sound in silent mode and even when it goes to background, try this:
Put this code in application:didFinishLaunchingWithOpitons:
[[AVAudioSession sharedInstance] setDelegate:self];
[[AVAudioSession sharedInstance] setCategory:AVAudioSessionCategoryPlayback error:nil];
[[AVAudioSession sharedInstance] setActive:YES error:nil];
[[UIApplication sharedApplication] beginReceivingRemoteControlEvents];
and this code in applicationDidEnterBackground:
[[UIApplication sharedApplication] beginBackgroundTaskWithExpirationHandler:NULL];
[[UIApplication sharedApplication] beginReceivingRemoteControlEvents];
Also setup a background mode of Playing Audio/Air Play and include AVFoundation header.
for Objective C, you could play system sound with following code:
[[AVAudioSession sharedInstance] setCategory:AVAudioSessionCategoryPlayback error:nil];
*The system path could be modified.*
NSString *path = #"/System/Library/Audio/UISounds/begin_record.caf";
NSURL *url = [NSURL fileURLWithPath:path];
player = [[AVAudioPlayer alloc] initWithContentsOfURL:url error:nil];
[player play];
Swift - Call this function before playing your audio/video to force playback when the phone is on silent. This also silences other audio that is currently playing.
You can change .duckOthers to .mixWithOthers if you don't want to silence other audio.
func setupAudio() {
let audioSession = AVAudioSession.sharedInstance()
_ = try? audioSession.setCategory(AVAudioSessionCategoryPlayback, with: .duckOthers)
_ = try? audioSession.setActive(true)
}
Can AVPlayer place MP3 files?
It does not list MP3 in the apple documentation.
Did u try using
[[AVAudioPlayer alloc]initWithContentsOfURL:fileUrl error:nil];
to play the file
Yes it can play MP3.
Try reading the apple documentation here and specifically the section entitled "iOS Hardware and Software Audio Codecs"
Here is a complete sample.
myClass.h:
- #interface myClass : NSObject \<AVAudioPlayerDelegate\> ...
myClass.m:
localPlayer = [[AVAudioPlayer alloc]
initWithContentsOfURL:newAudioURL error:nil]; [localPlayer
setDelegate:self];
- (void)audioPlayerDidFinishPlaying:(AVAudioPlayer *)playedPlayer successfully:(BOOL)flag {
NSLog(#"releasing");
[playedPlayer release];
NSLog(#"released"); }
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. :)
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);