I have always used audio toolbox to play my sounds, but users have saying there is no sound, this is because when you are on silent it doesnt play. I have tried many times to swap instead to av foundation but it never works for me. this is the code i am attempting to use now:
- (IBAction)soundbutton:(id)sender {
NSString *path = [[NSBundle mainBundle] pathForResource:#"EASPORTS" ofType:#"mp3"];
AVAudioPlayer * theAudio=[[AVAudioPlayer alloc] initWithContentsOfURL:[NSURL fileURLWithPath:path] error:NULL];
[theAudio play];}
Reason could be that in ARC your audio player is being released by ARC, therefore you need to make a strong reference of the AVAudioPlayer, you can do that by making the AVAudioPlayer as class level property.
here is how you do it, in your .h file like this
#property (strong, nonatomic) AVAudioPlayer *theAudio;
and in .m file synthesize it like this
#synthesize theAudio;
and finally your code would look like this
- (IBAction)soundbutton:(id)sender {
NSString *path = [[NSBundle mainBundle] pathForResource:#"EASPORTS" ofType:#"mp3"];
self.theAudio=[[AVAudioPlayer alloc] initWithContentsOfURL:[NSURL fileURLWithPath:path] error:nil];
[self.theAudio play];
}
check also if your delegate methods are responding something
- (void)audioPlayerDidFinishPlaying:(AVAudioPlayer *)player successfully:(BOOL)flag;
- (void)audioPlayerDecodeErrorDidOccur:(AVAudioPlayer *)player error:(NSError *)error;
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!
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 am trying to play a sound on button click using the AVFoundation framework. Previously, i used audio toolbox however when i use the audioplayer nothing comes out. What is weird is that when i test it on my phone and i press the button, the volume controls aren't the normal ringer volume controls. This suggests that it should be playing but i can't hear anything, on my phone or the simulator. I have used different files, created new project changed the code, nothing has helped.
Here's the code in .h:
#interface MainViewController : UIViewController <AVAudioPlayerDelegate>
- (IBAction)test;
Here's the code in .m:
- (IBAction)test {
NSString *path = [[NSBundle mainBundle] pathForResource:#"sound" ofType:#"mp3"];
AVAudioPlayer* theAudio = [[AVAudioPlayer alloc]initWithContentsOfURL:[NSURL fileURLWithPath:path] error:NULL];
theAudio.delegate = self;
[theAudio play];
}
can you do this before you play the sound i think you might have the wrong category:
AudioSessionInitialize (NULL,NULL,NULL,NULL);
UInt32 sessionCategory = kAudioSessionCategory_MediaPlayback;
AudioSessionSetProperty (kAudioSessionProperty_AudioCategory,sizeof (sessionCategory),&sessionCategory);
AudioSessionSetActive(true);
I have a ViewController : GLKViewController
with this code:
- (void)viewDidLoad
{
[super viewDidLoad];
NSString *path = [[NSBundle mainBundle] pathForResource:#"background-music-aac" ofType:#"caf"];
NSURL *url = [NSURL URLWithString:path];
NSData *data = [NSData dataWithContentsOfURL:url];
AVAudioPlayer *audio = [[AVAudioPlayer alloc] initWithData:data error:nil];
audio.delegate = self;
audio.volume = 1.0;
audio.numberOfLoops = -1;
[audio prepareToPlay];
[audio play];
[self setupContext];
[self setupDisplay];
}
However... my graphical things working fine but the iOS simulator plays no music.
did I something wrong?
Assuming you are using ARC, the player is getting deallocated as soon your method returns to its caller. To quote from this answer:
ARC inserts a release call to the audio player, so it's deallocated right after leaving the method where it is created.
Try implementing the AVAudioPlayer as a property.
If your data is nil, the file was not properly added to the project. To add your file to the project, just drag and drop it and add it to your targets.
Also, AVAudioPlayer has a method, initWithContentsOfURL:, which you might want to use.
I'm trying to figure out why sounds aren't playing in my app, so I created what I think is as simple an implementation as possible:
NSError *error;
NSString *soundFilePath = [[NSBundle mainBundle] pathForResource:#"canary-trills" ofType:#"wav"];
NSLog(#"string=%#", soundFilePath);
NSURL *url = [[NSURL alloc] initFileURLWithPath:soundFilePath];
NSLog(#"URL=%#", url);
AVAudioPlayer *avPlayer = [[AVAudioPlayer alloc]
initWithContentsOfURL:url error:&error];
[avPlayer prepareToPlay];
BOOL success = [avPlayer play];
NSLog(#"The sound %# play", success ? #"did" : #"didn't");
Per the console, it looks like it finds the resource, creates the URL correctly. Even the play call indicates success. However, no sound play in the simulator nor the device.
AVAudioPlayer wasn't being retained & was going out of scope.
Adding:
#property (strong, nonatomic) AVAudioPlayer *audioPlayer;
to the class & using that member solved the issue.