I have been trying to play an audio file but unable to succeed.
SoundFilePath:
/Users/admin/Library/Containers/com.abc.myApp/Data/Documents/MyAudioSample1.wav
NSSound:
NSSound *sound = [[NSSound alloc] initWithContentsOfFile:soundFilePath byReference:YES];
sound.volume = 1;
sound.delegate = self;
[sound play];
Only once out of 5 times my audio is played.
AVFoundation:
NSURL* file = [NSURL fileURLWithPath:soundFilePath];
AVAudioPlayer *audioPlayer = [[AVAudioPlayer alloc] initWithContentsOfURL:file error:nil];
[audioPlayer prepareToPlay];
Add [audioPlayer play];
You are preparing to play but not playing it. After adding above line your code will be:
NSURL* file = [NSURL fileURLWithPath:soundFilePath];
AVAudioPlayer *audioPlayer = [[AVAudioPlayeralloc]initWithContentsOfURL:file error:nil];
[audioPlayer prepareToPlay];
[audioPlayer play];
Hope it helps
I'm trying to play a sound using AVAudioPlayer on os x (not iOS!). I'm using the following code:
AVAudioPlayer *player;
NSString *soundFilePath = [[NSBundle mainBundle] pathForResource:name ofType:#"mp3"];
NSURL *soundFileURL = [NSURL fileURLWithPath:soundFilePath];
player = [[AVAudioPlayer alloc] initWithContentsOfURL:
soundFileURL error:&err];
if( err ){
NSLog(#"Failed with reason: %#", [err localizedDescription]);
}
else{
player.delegate = self;
player.numberOfLoops = -1;
player.currentTime = 0;
player.volume = 1.0;
[player play];
}
All is ok, and the player calls play function without the errors. However I can't hear any sound after that. I'm sure that my audio file is ok, because I was able to play it using NSSound class. The reason I want to use AVAudioPlayer is that when I'm using NSSound class and I play it in a loop there is short pause in between and that's why I wanted to try AVAudioPlayer.
Define the *player as a property so it gets not evaporated after your method finishes.
I have implemented AVAudiorecorder for recording and playing voice for 10 secs.it is working fine with iOS 7.But when i run the same code on ios8 ,it is not working please help.
Here is a source Code.
//Below is my code for recording and Playing.
//Here is the Recording code which records sound for 10 secs
AVAudioSession *audioSession = [AVAudioSession sharedInstance];
NSError *err = nil;
[audioSession setCategory :AVAudioSessionCategoryPlayAndRecord error:&err];
if(err){
return;
}
[audioSession setActive:YES error:&err];
err = nil;
// Setup audio recording
recordSetting = #{AVFormatIDKey: #(kAudioFormatMPEG4AAC),
AVEncoderAudioQualityKey: #(AVAudioQualityLow),
AVNumberOfChannelsKey: #1,
AVSampleRateKey: #22050.0f};
recorderFilePath = [NSString stringWithFormat:#"%#/MySound.wave", DOCUMENTS_FOLDER];
NSData *postData = [NSData dataWithContentsOfFile:recorderFilePath];
NSURL *url = [NSURL fileURLWithPath:recorderFilePath];err = nil;
NSData *audioData = [NSData dataWithContentsOfFile:[url path] options: 0 error:&err];
if(audioData)
{NSFileManager *fm = [NSFileManager defaultManager];
[fm removeItemAtPath:[url path] error:&err];}
err = nil;
recorder = [[ AVAudioRecorder alloc] initWithURL:url settings:recordSetting error:&err];
//prepare to record
[recorder setDelegate:self];
[recorder prepareToRecord];
recorder.meteringEnabled = YES;
//Please help me out and tell if i have to add/modify something because it is working in ios7.
It seems that there isn't nothing wrong in your code snippet.
I use approximately the same code to make a registration on my iPhone, too.
The only difference with my code is a call to
[recorder recordForDuration:(NSTimeInterval) 10];
in order to start the registration for 10 seconds
I have very common question as i searched for it but cant get the correct answer for me.
here is the piece of code on which I m trying hard to play Audio files.
in viewDidLoad method:
NSURL *buttonSound = [NSURL fileURLWithPath:[NSString stringWithFormat:#"%#/button4.wav", [[NSBundle mainBundle] resourcePath]]];
NSURL *correctSound = [NSURL fileURLWithPath:[NSString stringWithFormat:#"%#/key_drop1.wav", [[NSBundle mainBundle] resourcePath]]];
NSURL *wrongSound = [NSURL fileURLWithPath:[NSString stringWithFormat:#"%#/sound8.mp3", [[NSBundle mainBundle] resourcePath]]];
NSError *error;
ButtonPressedSound = [[AVAudioPlayer alloc] initWithContentsOfURL:buttonSound error:&error];
ButtonPressedSound.numberOfLoops = 0;
correctAnsweredSound = [[AVAudioPlayer alloc] initWithContentsOfURL:correctSound error:&error];
correctAnsweredSound.numberOfLoops = 0;
wrongAnsweredSound = [[AVAudioPlayer alloc] initWithContentsOfURL:wrongSound error:&error];
wrongAnsweredSound.numberOfLoops = 0;
in IBAction of pressing a button m calling "play" in this way.
[ButtonPressedSound play];
[self performSelector:#selector(stop) withObject:nil afterDelay:0.50];
[correctAnsweredSound play];
[self performSelector:#selector(stop) withObject:nil afterDelay:0.50];
[wrongAnsweredSound play];
[self performSelector:#selector(stop) withObject:nil afterDelay:1.0];
my play and stop methods are :
-(IBAction)play
{
self.ButtonPressedSound.currentTime = 0;
[self.ButtonPressedSound play];
self.correctAnsweredSound.currentTime = 0;
[self.correctAnsweredSound play];
self.wrongAnsweredSound.currentTime = 0;
[self.wrongAnsweredSound play];
}
-(IBAction)stop
{
[self.ButtonPressedSound stop];
[self.correctAnsweredSound stop];
[self.wrongAnsweredSound stop];
}
what I have done so far...
I have searched to these links but not get the answer for my code.
AVAudioPlayer only plays in simulator but not device why?! (iPhone-SDK)
mp3 Sounds Playing on simulator but not on Device (Audio BeatBox)
http://www.icodeblog.com/2009/05/04/iphone-game-programming-tutorial-part-4-basic-game-audio/
...........
I have checked all the names n there is not any typo mistake.
Dont know where m getting wrong , pls help !!!
I've had similar problems before, but this solution is just a random guess that worked for me at the time.
On the real iPhone, file paths are case-sensitive. On the simulator, they are not. So I would check to make sure your file paths are exactly correct, including case.
I want to play music even if the app goes in background. I checked all stackoverflow links but none of them worked. Please help need to do it today.
I had used following code:-
NSString *soundFilePath = [[NSBundle mainBundle] pathForResource:#"Day At The Beach" ofType: #"mp3"];
NSURL *fileURL = [[NSURL alloc] initFileURLWithPath: soundFilePath];
NSError *error;
playerTemp = [[AVAudioPlayer alloc] initWithContentsOfURL:fileURL error:&error];
playerTemp.numberOfLoops = 0;
AudioSessionSetActive(true);
[playerTemp play];
I had solved this question by referring iOS Application Background tasks
and make some changes in .plist file of our application..
Update
write this code in your controller's view did load method like this
- (void)viewDidLoad
{
NSURL *url = [NSURL fileURLWithPath:[[NSBundle mainBundle] pathForResource:#"in-the-storm" ofType:#"mp3"]];
AVAudioPlayer *audioPlayer = [[AVAudioPlayer alloc] initWithContentsOfURL:url error:nil];
[[AVAudioSession sharedInstance] setCategory:AVAudioSessionCategoryPlayback error:nil];
[[AVAudioSession sharedInstance] setActive: YES error: nil];
[[UIApplication sharedApplication] beginReceivingRemoteControlEvents];
[audioPlayer play];
[super viewDidLoad];
}
I just wanted to add a note to Mehul's answer. This line:
[[UIApplication sharedApplication] beginReceivingRemoteControlEvents];
is actually very important. I used other tutorials to get my AVAudioPlayer up and running. Everything worked fine except my audio would not START if the app was in the background. To clarify, my audio was fine if it was already playing when the app went into the background...but it would not start if the app was already in the background.
Adding the above line of code made it so my audio would start even if the app was in the background.
You need to set 'audio' as one of your UIBackgroundModes in Info.plist. Apple has documentation on the issue.
Write this line in to plist for background run...
<key>UIBackgroundModes</key>
<array>
<string>audio</string>
</array>
Write this code Where you want to use
AVAudioPlayer* audioPlayer = [[AVAudioPlayer alloc] initWithContentsOfURL:self.urlForConevW error:&error];
audioPlayer.delegate = self;
[[AVAudioSession sharedInstance] setCategory:AVAudioSessionCategoryPlayback error:nil];
[[AVAudioSession sharedInstance] setActive: YES error: nil];
[[UIApplication sharedApplication] beginReceivingRemoteControlEvents];
audioPlayer.numberOfLoops = 1;
[audioPlayer play];
Step1
Make the following changes in info.plist
Application does not run in background : NO
Required background modes
item0 :App plays audio or streams audio/video using AirPlay
Step 2
Don't forget to add the following things in MainViewController.h file
#import <'AVFoundation/AVAudioPlayer.h>
#interface MainViewController:<'AVAudioPlayerDelegate>
AVAudioPlayer *H_audio_player;
Step 3
Add the following code inside the play action of your MainViewController class.
NSString *soundFilePath = [[NSBundle mainBundle] pathForResource:[NSString stringWithFormat:#"%d-%d",C_CID, C_SID] ofType:#"mp3"];
NSURL *soundFileURL = [NSURL fileURLWithPath:soundFilePath];
H_audio_player = [[AVAudioPlayer alloc] initWithContentsOfURL:soundFileURL error:nil];
H_audio_player.delegate = self;
H_audio_player.numberOfLoops = -1;
Also important here if you are using MPMusicPlayerController:
You must use:
[MPMusicPlayerController iPodMusicPlayer]
And Not
[MPMusicPlayerController applicationMusicPlayer]
Also if you don't want your app to stop music which was playing when your app is started, look here:
AVAudioPlayer turns off iPod - how to work around?
You can use MPMoviePlayerController even to play solo-audio movies. If you like it, read this detailed Apple Library Technical Q&A:
iOS Developer Library Technical Q&A QA1668
I use the below code. It work for me, and call on the button click of audio player instance method.
NSError *error; NSURL *url = [NSURL fileURLWithPath:[[NSBundle mainBundle] pathForResource:#"music" ofType:#"mp3"]];
self.player = [[AVAudioPlayer alloc] initWithContentsOfURL:url error:nil];
[[AVAudioSession sharedInstance] setCategory:AVAudioSessionCategoryPlayback error:&error];
[[AVAudioSession sharedInstance] setActive:YES error: &error];
[[UIApplication sharedApplication] beginReceivingRemoteControlEvents];
[self.player prepareToPlay];
From all answers is missing this code to control the player when user is waking the device:
- (BOOL)canBecomeFirstResponder {
return YES;
}
- (void)remoteControlReceivedWithEvent:(UIEvent *)event {
switch (event.subtype) {
case UIEventSubtypeRemoteControlPlay:
[_audioPlayer play];
break;
case UIEventSubtypeRemoteControlPause:
[_audioPlayer pause];
break;
default:
break;
}
}
And you have all these options:
UIEventSubtypeRemoteControlPlay = 100,
UIEventSubtypeRemoteControlPause = 101,
UIEventSubtypeRemoteControlStop = 102,
UIEventSubtypeRemoteControlTogglePlayPause = 103,
UIEventSubtypeRemoteControlNextTrack = 104,
UIEventSubtypeRemoteControlPreviousTrack = 105,
UIEventSubtypeRemoteControlBeginSeekingBackward = 106,
UIEventSubtypeRemoteControlEndSeekingBackward = 107,
UIEventSubtypeRemoteControlBeginSeekingForward = 108,
UIEventSubtypeRemoteControlEndSeekingForward = 109,
If even after setting audio as one of your UIBackgroundModes in the plist the audio stops when going to background, try setting your application's audio session to media playback.
Here's the related reference:
https://developer.apple.com/library/ios/documentation/Audio/Conceptual/AudioSessionProgrammingGuide/Introduction/Introduction.html
Here's about what the code's gonna look like:
NSError *activationError = nil;
[[AVAudioSession sharedInstance] setActive: YES error: &activationError];
NSError*setCategoryError = nil;
[[AVAudioSession sharedInstance] setCategory: AVAudioSessionCategoryPlayback error: &setCategoryError];
To play your audio in background
Step 1 :Just add in your info.plistmake an array
step2 :
- (void)applicationDidEnterBackground:(UIApplication *)application
{
__block UIBackgroundTaskIdentifier task = 0;
task=[application beginBackgroundTaskWithExpirationHandler:^{
NSLog(#"Expiration handler called %f",[application backgroundTimeRemaining]);
[application endBackgroundTask:task];
task=UIBackgroundTaskInvalid;
}];
}
step3 :
NSString *soundFilePath = [[NSBundle mainBundle] pathForResource:#"iNamokar" ofType:#"mp3"];
NSURL *fileURL = [[NSURL alloc] initFileURLWithPath:soundFilePath];
AVAudioPlayer *newPlayer = [[AVAudioPlayer alloc] initWithContentsOfURL:fileURL error:nil];
[[AVAudioSession sharedInstance] setCategory:AVAudioSessionCategoryPlayback error:nil];
[[AVAudioSession sharedInstance] setActive: YES error: nil];
[[UIApplication sharedApplication] beginReceivingRemoteControlEvents];
[player prepareToPlay];
[self.player play];
From Apple's sample code: Audio Mixer (MixerHost)
// If using a nonmixable audio session category, as this app does, you must activate reception of
// remote-control events to allow reactivation of the audio session when running in the background.
// Also, to receive remote-control events, the app must be eligible to become the first responder.
- (void) viewDidAppear: (BOOL) animated {
[super viewDidAppear: animated];
[[UIApplication sharedApplication] beginReceivingRemoteControlEvents];
[self becomeFirstResponder];
}
I think remote control events are not needed for the following case:
AudioSessionSetProperty(kAudioSessionProperty_OverrideCategoryMixWithOthers,
sizeof(value), &value);