I have the following code in my viewcontroller. When I run, the audio doesn't play in the xcode simulator. Any advice on what I should do?
Also, I've saved anomaly.mp3 in the same directory (no sub-folders) as ViewController.m.
#import <AVFoundation/AVFoundation.h> //before viewDidLoad
NSError * error = nil;
NSURL *url = [NSURL fileURLWithPath:[[NSBundle mainBundle]
pathForResource:#"anomaly"
ofType:#"mp3"]];
AVAudioPlayer *audioPlayer = [[AVAudioPlayer alloc]
initWithContentsOfURL:url
error:&error];
if (error){
NSLog(#"error: %#", [error localizedDescription]);
}
NSLog(#"test");
[audioPlayer play];
Try setting the audio player's volume. You can also check the results of the "play" function, to see if things worked correctly. The play function implicitly calls prepareToPlay. This function can fail out for a number of reasons, irritatingly without any error object or message...
NSError * error = nil;
NSURL *url = [NSURL fileURLWithPath:[[NSBundle mainBundle]
pathForResource:#"anomaly"
ofType:#"mp3"]];
AVAudioPlayer *audioPlayer = [[AVAudioPlayer alloc]
initWithContentsOfURL:url
error:&error];
if (error){
NSLog(#"error: %#", [error localizedDescription]);
} else {
audioPlayer.volume = 50;
if([audioPlayer play]) NSLog(#"Should be playing");
else NSLog(#"Something weird happened"); //usually related to unavailable hardware
}
Keep a strong reference to the audioPlayer by declaring it as:
#property (nonatomic) AVAudioPlayer *audioPlayer;
and then use self.audioPlayer wherever you have used audioPlayer.
The problem with your code is that because your audioPlayer is just a local variable to the method, it gets deallocated by ARC as soon as your method is completed. Keeping a strong reference to it will keep the audioPlayer object and memory and your sound will keep playing as long as you don't call
[self.audioPlayer stop];
Related
Here is my code, In this first I am calling mp3 url for downloading the audio data. then I am saving that data in local directory, After that I am playing audio from local file path but its not working AVAudioPlayer throwing error. I have tried some other ways also but no one work for me.
On simulator same code is working fine.
And the audio url is playing like a charm in browser.
NSURL *urlll=[NSURL URLWithString:#"www.xyz.audio.mp3"];
[NSURLConnection sendAsynchronousRequest:[NSURLRequest requestWithURL:urlll] queue:[NSOperationQueue mainQueue] completionHandler:^(NSURLResponse *responce,NSData* data,NSError * error) {
if (error == nil)
{
indicator.hidden=YES;
[indicator stopAnimating];
if (data)
{
NSString *docDirPath = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0];
NSString *filePath = [NSString stringWithFormat:#"%#/%#.mp3", docDirPath , #"Audio"];
[data writeToFile:filePath atomically:YES];
NSURL *fileURL = [NSURL fileURLWithPath:filePath];
AudioPlayer = [[AVAudioPlayer alloc] initWithContentsOfURL:fileURL error:&error];
AudioPlayer.delegate=self;
[AudioPlayer prepareToPlay];
if (AudioPlayer == nil) {
NSLog(#"AudioPlayer did not load properly: %#", [error description]);
} else {
[AudioPlayer play];
}
}
}
}];
But I am getting these kind of errors : Error Domain=NSOSStatusErrorDomain Code=1685348671 "The operation couldn't be completed. (OSStatus error 1685348671.)
Please Help me :( .
In your code you save the audio to NSString *filePath but you initiate with fileURL. Could it be that you actually wanted to do this:
AudioPlayer = [[AVAudioPlayer alloc] initWithContentsOfURL:[NSURL URLWithString:filePath] error:&error];
If not then you should know that the error is reporting to you a kAudioFileInvalidFileError. Which means the file is malformed. You could try other formats like .caf or .aifc or aiff.
--edit--
Make sure the AVAudioPlayer is a property in .m or .h file, so the memory allocation lasts after leaving the method:
#property (nonatomic,strong) AVAudioPlayer *AudioPlayer;
(side note: properties should start with lowercase -> audioPlayer)
I am having trouble with my audio.
here is the code:
AVAudioPlayer *audioPlayer;
NSString *audioPath = [[NSBundle mainBundle]pathForResource:#"Cheering" ofType:#"mp3"];
NSURL *audioURL = [NSURL fileURLWithPath:audioPath];
audioPlayer = [[AVAudioPlayer alloc] initWithContentsOfURL:audioURL error:nil];
[audioPlayer play];
It will not play like this. The code steps through just fine but no audio. If I put a break on the last line and then step through it plays properly. I have tried everything I can to get this to work but have no clue where to go from here.
It is acting like it needs a delay before the play command.
Try this Sure It will Works
NSURL* url = [[NSBundle mainBundle] URLForResource:#"Cheering" withExtension:#"mp3"];
NSAssert(url, #"URL is valid.");
NSError* error = nil;
audioPlayer = [[AVAudioPlayer alloc] initWithContentsOfURL:url error:nil];
if(!audioPlayer)
{
NSLog(#"Error creating player: %#", error);
} else
{
[audioPlayer play];
}
Did you try
[audioPlayer prepareToPlay]
before you actually try to play it?
https://developer.apple.com/library/ios/DOCUMENTATION/AVFoundation/Reference/AVAudioPlayerClassReference/Reference/Reference.html#//apple_ref/occ/instm/AVAudioPlayer/prepareToPlay
I'm following in a tutorial on how to play mp3 sounds when pressing a button.
I created a button (playSound).
I added it to the view controller interface:
- (IBACTION)playSound:(id)sender;
in the implementation I declared the needed header files and I wrote the following:
#import "AudioToolbox/AudioToolbox.h"
#import "AVFoundation/AVfoundation.h"
- (IBAction)playSound:(id)sender {
//NSLog(#"this button works");
AVAudioPlayer *audioPlayer;
NSString *audioPath = [[NSBundle mainBundle] pathForResource:#"audio" ofType:#"mp3"];
//NSLog(#"%#", audioPath);
NSURL *audioURL = [NSURL fileURLWithPath:audioPath];
//NSLog(#"%#", audioURL);
audioPlayer = [[AVAudioPlayer alloc] initWithContentsOfURL:audioURL error:nil];
[audioPlayer play];
}
I'm not getting any errors. the NSlogs are logging the URL fine, and now I have no clue where to look further. I also checked if my MP3 sound was maybe damaged, but that was also not the case. all i hear is a little crackling noise for 1 second. then it stops.
You declared a local variable audioPlayer to hold a pointer to the player. As soon as your button handler returns the player is being released before it has a chance to play your sound file. Declare a property and use it instead of the local variable.
In YourViewController.m file
#interface YourViewController ()
#property (nonatomic, strong) AVAudioPlayer *audioPlayer;
#end
or in YourViewController.h file
#interface YourViewController : UIViewController
#property (nonatomic, strong) AVAudioPlayer *audioPlayer;
#end
Then replace audioPlayer with self.audioPlayer in your code.
try this its working for me
in .h
AVAudioPlayer * _backgroundMusicPlayer;
in .m
NSString *backgroundMusicPath = [[NSBundle mainBundle] pathForResource:#"Theme" ofType:#"mp3"];
NSURL *backgroundMusicURL = [NSURL fileURLWithPath:backgroundMusicPath];
NSError *error;
_backgroundMusicPlayer = [[AVAudioPlayer alloc] initWithContentsOfURL:backgroundMusicURL error:&error];
[_backgroundMusicPlayer setDelegate:self]; // We need this so we can restart after interruptions
[_backgroundMusicPlayer setNumberOfLoops:-1];
[_backgroundMusicPlayer play];
Edited
NSString *soundFilePath = [[NSBundle mainBundle] pathForResource:#"Name of your audio file"
ofType:#"type of your audio file example: mp3"];
NSURL *soundFileURL = [NSURL fileURLWithPath:soundFilePath];
audioPlayer = [[AVAudioPlayer alloc] initWithContentsOfURL:soundFileURL error:nil];
audioPlayer.numberOfLoops = -1;
audioPlayer.delegate=self;
[audioPlayer play];
Try this and let me know. Make sure you set the delegate for audioPlayer.
Firstly re add your music file in your project , then try this code
With the log you can see error.
NSError *error;
NSURL *url = [NSURL fileURLWithPath:[[NSBundle mainBundle] pathForResource:#"bg_sound" ofType:#"mp3"]];
AVAudioPlayer *audioPlayer = [[AVAudioPlayer alloc]
initWithContentsOfURL:url
error:&error];
if (error){
//Print Error
NSLog(#"Error in audioPlayer: %#",
[error localizedDescription]);
} else {
audioPlayer.delegate = self;
[audioPlayer prepareToPlay];
[audioPlayer setNumberOfLoops: -1];
[audioPlayer play];
audioPlayer.volume=1.0;
}
Make sure your music files are properly added in project
I’m trying to play a sound using the AVAudioPlayer without success. I’ve tried it both in the iOS Simulator and on my iPhone. I don’t get any errors, but I also don’t hear a sound.
Here’s my code:
NSString *soundFilePath = [[NSBundle mainBundle] pathForResource: #"RiggerSound_Click" ofType: #"wav"];
NSLog( #"Path is %#", soundFilePath );
NSURL *fileURL = [[NSURL alloc] initFileURLWithPath: soundFilePath];
NSError *error;
AVAudioPlayer *newPlayer = [[AVAudioPlayer alloc] initWithContentsOfURL: fileURL error: &error];
[fileURL release];
if (newPlayer != nil)
{
if( ![newPlayer play] )
NSLog( #"Error playing" );
[newPlayer release];
}
else
NSLog(#"Error creating audioPlayer: %#", [error localizedDescription]);
The soundFilePath is “/Users/myname/Library/Application Support/iPhone Simulator/6.1/Applications/E50059DD-B328-45C7-A5D5-C650F415B183/appname.app/RiggerSound_Click.wav”.
The “newPlayer” variable is not null and [newPlayer play] does not fail.
The file “RiggerSound_Click.wav” is shown in the Resources folder of my project. I can select it in the project, click the Play button, and hear the sound.
I’m stumped.
Thanks for your help.
Set the AVAudioPlayer's delegate before playing. For example,
newPlayer.delegate = self;
Also, make sure your delegate's class conforms to the AVAudioPlayerDelegate protocol:
MyClass : Superclass <AVAudioPlayerDelegate>
Just define the AVAudio Player as static
static AVAudioPlayer *newPlayer = Nil;
if(newPlayer == Nil)
{
newPlayer = [[AVAudioPlayer alloc] initWithContentsOfURL: fileURL error: &error];
}
That's it
I get an error trying to play a clip using AVAudioPlayer. The error gives me:
'The operation couldn’t be completed. (OSStatus error -50.)'
I have no idea. The frameworks are all there etc...
Is it something to do with the URL?
Here's my code:
NSString *soundFilePath = [[NSBundle mainBundle] pathForResource:#"grunt" ofType:#"aiff"];
NSURL *fileURL = [NSURL URLWithString:soundFilePath];
NSError *error;
audioPlayer = [[AVAudioPlayer alloc] initWithContentsOfURL:fileURL error:&error];
if(!error){
audioPlayer.delegate = self;
[audioPlayer play];
}else{
NSLog(#"Error loading clip: %#", [error localizedDescription]);
}
Thanks in advance!
have you tried NSURL +fileURLWithPath?