AVAudioPlayer delegate wont get called in a class method? - ios

i am using the AVAudioPlayer and setting its delegate but its delegate is not getting called
+ (void) playflip
{
NSString *path;
path = [[NSBundle mainBundle] pathForResource:#"flip" ofType:#"mp3"];
AVAudioPlayer *flip;
flip = [[AVAudioPlayer alloc] initWithContentsOfURL:[NSURL fileURLWithPath:path] error:Nil];
flip.delegate = self;
[flip play];
}
My class where i am implementing is the sound class
#interface SoundClass : NSObject <AVAudioPlayerDelegate>
I am calling this delegate
- (void)audioPlayerDidFinishPlaying:(AVAudioPlayer *)player successfully:(BOOL)flag
{
NSLog(#"delegate called");
[player release];
player = nil;
}

It looks like maybe your flip object is going out of scope, because the rest of your code looks fine. Here's what I do:
// controller.h
#interface SoundClass : NSObject <AVAudioPlayerDelegate> {}
// #property(nonatomic,retain) NSMutableDictionary *sounds;
// I have lots of sounds, pre-loaded in a dictionary so that I can reference by name
// With one player, you can just use:
#property(nonatomic,retain) AVAudioPlayer *player;
Then allocate and load the sound in your .m
player = [[AVAudioPlayer alloc] initWithContentsOfURL:[NSURL fileURLWithPath:path] error:Nil];
[player prepareToPlay];
player.delegate = self;
[player play];
Now you should get your DidFinishPlaying notification.

Related

How to play .caf audio file from server url in ios

I try to play audio from server url but nothing play, But i try to play audio from document directory path url and it play fine.
NSData *songData=[NSData dataWithContentsOfURL:[NSURL URLWithString:
[NSString stringWithFormat:#"%#",aSongURL]]];
AVAudioPlayer *abc = [[AVAudioPlayer alloc] initWithData:songData error:nil];
abc.numberOfLoops=0;
[abc prepareToPlay];
[abc play];
You can try this. Hope it helps.
AVPlayer *objAVPlayer = [[AVPlayer alloc] initWithURL:url];
[objAVPlayer play];
My answer is below
ViewController.h
#import <UIKit/UIKit.h>
#import <AVFoundation/AVFoundation.h>
#interface ViewController : UIViewController
#property (nonatomic,strong)AVAudioPlayer *player;
- (IBAction)actionPlayAudio:(id)sender;
#end
ViewController.m
#import "ViewController.h"
#interface ViewController ()
#end
#implementation ViewController
#synthesize player;
- (void)viewDidLoad {
[super viewDidLoad];
}
- (IBAction)actionPlayAudio:(id)sender {
NSString *strAudioFileURL = #"dev.epixelsoft.co/love_app/audio/img_14957068361.caf";
NSURL *soundFileURL = [NSURL fileURLWithPath:strAudioFileURL];
player = [[AVAudioPlayer alloc] initWithContentsOfURL:soundFileURL error:nil];
[player play];
}

Looping .wav file

I am making an alarm app for iPhones and want to continuously loop the audio until the button is pressed again. As of now all it does is play the audio once when pressed. Here's the code:
-(IBAction)PlayAudioButton:(id)sender {
AudioServicesPlaySystemSound(PlaySoundID);
}
- (void)viewDidLoad {
NSURL *SoundURL = [NSURL fileURLWithPath:[[NSBundle mainBundle] pathForResource:#"Sound" ofType:#"wav"]];
AudioServicesCreateSystemSoundID((__bridge CFURLRef)SoundURL, &PlaySoundID);
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
}
Any suggestions?
Use AVAudioPlayer to play the sound. You must add AVFoundation.framework to your project for this to work. Start by declaring an AVAudioPlayer object. It must be declared either as a property with a strong attribute, e.g.
#property (strong, nonatomic) AVAudioPlayer *audioPlayer;
or as an instance variable with a __strong attribute
#interface Class : SuperClass //or #implementation Class
{
AVAudioPlayer __strong *audioPlayer;
}
Then, to load and play the file,
- (void)viewDidLoad
{
NSString *audioFilePath = [[NSBundle mainBundle] pathForResource:#"Sound" ofType:#"wav"];
NSURL *audioFileURL = [NSURL fileURLWithString:audioFilePath];
audioPlayer = [[AVAudioPlayer alloc] initWithContentsOfURL:audioFileURL error:nil];
audioPlayer.numberOfLoops = -1; //plays indefinitely
[audioPlayer prepareToPlay];
}
- (IBAction)PlayAudioButton:(id)sender
{
if ([audioPlayer isPlaying])
[audioPlayer pause]; //or "[audioPlayer stop];", depending on what you want
else
[audioPlayer play];
}
and, when you want to stop playing the sound, call
[audioPlayer stop];

Why don't I hear music?

So I have an app where I want to include background music. I use the following code for the music:
.h: (I did also add the framework)
#import <UIKit/UIKit.h>
#import <AVFoundation/AVFoundation.h>
#interface ViewController : UIViewController
{
AVAudioPlayer *player;
}
.m:
- (void)viewDidAppear:(BOOL)animated {
NSURL *url = [[NSBundle mainBundle] URLForResource:#"song" withExtension:#"mp3"];
player = [[AVAudioPlayer alloc] initWithContentsOfURL:url error:nil];
player.numberOfLoops = -1;
[player play];
NSLog(#"playing music");
}
The path for the music file is definitly correct. The app does not crash but I just do not hear any music.
By the way: the LogMessage ("playing music") appears in the debugger.
Any ideas?
Add prepareToPlay method before [player play];
[player prepareToPlay];
Hope this will work...

AVAudioPlayer not playing my mp3

I'm trying to get a short audio file (mp3) to play in my app. Here is the code i'm using:
AVAudioPlayer *AudioPlayer;
NSError *error;
NSURL *url = [NSURL fileURLWithPath:[[NSBundle mainBundle]
pathForResource:#"filename"
ofType:#"mp3"]];
AudioPlayer = [[AVAudioPlayer alloc] initWithContentsOfURL:url error:&error];
AudioPlayer.delegate = self;
[[AVAudioSession sharedInstance] setCategory:AVAudioSessionCategoryPlayback error:nil];
if (error)
{
NSLog(#"Error: %#",
[error localizedDescription]);
}
else
{
[AudioPlayer play];
}
I don't really know what i'm missing, the examples i've followed seem to match what i'm doing.
edit: I should also mention that the code runs without error, there is a try catch around this.
I had a similar problem due to ARC. Instead of defining the AVAudioPlayer in the same method you are using it, you should should have an instance variable somewhere else, such as the UIViewController. This way ARC doesn't auto release this object and audio can play.
I've made some additions and got it work:
#import <UIKit/UIKit.h>
#import <AVFoundation/AVFoundation.h>
#interface FirstViewController : UIViewController <AVAudioPlayerDelegate> {
AVAudioPlayer *data;
UIButton *playButton_;
}
#property(nonatomic, retain) IBOutlet UIButton *playButton;
-(IBAction)musicPlayButtonClicked:(id)sender;
#end
#import "ViewController.h"
#implementation FirstViewController
#synthesize playButton=playButton_;
- (IBAction)musicPlayButtonClicked:(id)sender {
NSString *name = [[NSString alloc] initWithFormat:#"09 No Money"];
NSString *source = [[NSBundle mainBundle] pathForResource:name ofType:#"mp3"];
if (data) {
[data stop];
data = nil;
}
data=[[AVAudioPlayer alloc] initWithContentsOfURL:[NSURL fileURLWithPath: source] error:NULL];
data.delegate = self;
[data play];
}
- (void)viewDidLoad
{
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
}
- (void)didReceiveMemoryWarning
{
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
#end
In Interface Builder I've added a button and connected it with IBOutlet and musicPlayButtonClicked IBAction.
And don't forget to add AVFoundation framework to your project.
ps
I'm really sorry for my english, please, be indulgent.
I had this problem myself, until I found out that the sound was not coming through the speakers (instead - it was redirected to the calls speaker). Try adding this to redirect the sound through the speakers:
UInt32 doChangeDefaultRoute = 1;
AudioSessionSetProperty (kAudioSessionProperty_OverrideCategoryDefaultToSpeaker,
sizeof (doChangeDefaultRoute),
&doChangeDefaultRoute);

Passing data to my custom NSObject?

I have attempted to create my first custom class "AudioPlayer". I want to pass data (the audio title) from a tableview to my "AudioPlayer" and load the AudioPlayer with initWithContentsOfURL:[NSURL fileURLWithPath:path] but when I alloc the "AudioPlayer" in my "MainViewController" i get the error "Incompatible pointer types initializing 'Audio Player*___strong' with and expression of type AVAudioPLayer*". My question is, How would i initialize my custom audio player with the selected audio's title as the URL? It works fine when I created a variable of AVAudioPlayer, but I don't know how to pass it to my custom class.
Here is my custom class Header..
#import <Foundation/Foundation.h>
#import <AVFoundation/AVFoundation.h>
#import <AudioToolbox/AudioToolbox.h>
#interface AudioPlayer : NSObject{
AVAudioPlayer *audioPlayer;
//Volume slider
NSTimer *volumeTimer;
IBOutlet UISlider *volumeSlider;
}
-(bool) isPlaying;
-(bool) isPaused;
-(void)playPause:(id)sender;
#property (nonatomic, retain) AVAudioPlayer *audioPlayer;
#end
Here is my custom class implementation file...
#import "AudioPlayer.h"
#implementation AudioPlayer
#synthesize audioPlayer;
-(void)playPause{
if ([audioPlayer isPlaying]) {
[audioPlayer pause];
} else {
[audioPlayer play];
}
}
-(void)volumeSlider
{
//Setup the volume slider
volumeTimer = [NSTimer scheduledTimerWithTimeInterval:0 target:self selector:#selector(updateVolumeSlider) userInfo:nil repeats:YES];
[audioPlayer setVolume:volumeSlider.value];
}
#end
Here is the MainView implementation...
- (void)viewDidLoad
{
[super viewDidLoad];
//Instantiate performanceArray
performanceArray = [[NSMutableArray alloc]initWithObjects:#"Centering", nil];
//Instantiate recoveryArray
recoveryArray = [[NSMutableArray alloc]initWithObjects:#"Power Nap", nil];
//Instantiate the AudioPlayer
UITableViewCell *cell = [self.tableView cellForRowAtIndexPath:self.tableView.indexPathForSelectedRow];
NSString *path = [[NSBundle mainBundle] pathForResource:cell.textLabel.text ofType:#"m4a"];
AudioPlayer *audioPlayer = [[AVAudioPlayer alloc] initWithContentsOfURL:[NSURL fileURLWithPath:path] error:NULL];
[audioPlayer.audioPlayer prepareToPlay];
}
I think you are confusing your custom class with AVAudioPlayer class.
If you are trying to add more methods and options to the default class of AVAudioPlayer, you should subclass AVAudioPlayer rather than NSObject.
#import <Foundation/Foundation.h>
#import <AVFoundation/AVFoundation.h>
#import <AudioToolbox/AudioToolbox.h>
#interface AudioPlayer : AVAudioPlayer
// the rest of your code
and then as deanandreakis answered, you need to alloc/init your class rather than AVAudioPlayer.
meaning:
AudioPlayer *audioPlayer = [[AudioPlayer alloc] init];
Or you can use categories to add your custom methods added to AVAudioPlayer.
Your AudioPlayer object that you created is not of type AVAudioPlayer so I think the following line:
AudioPlayer *audioPlayer = [[AVAudioPlayer alloc] initWithContentsOfURL:[NSURL fileURLWithPath:path] error:NULL];
should be something like : AudioPlayer *audioPlayer = [[AudioPlayer alloc] init];
which would create an object of your custom class. You have at least a couple of options to then pass the NSURL information such as adding params to your custom classes init method or creating another property in your custom class that you set just after you create your object.
In your custom class AudioPlayer you could add a new my URL attribute:
#interface AudioPlayer : NSObject{
AVAudioPlayer *audioPlayer;
//Volume slider
NSTimer *volumeTimer;
IBOutlet UISlider *volumeSlider;
NSURL* myURL;
}
Then in your implementation file for AudioPlayer add the following init method:
-(id)initWithURL:(NSURL)theURL
{
self = [super init];
if (self) {
// perform initialization of object here
myURL = theURL;
}
return self;
}
And then in your MainView you could do something like:
NSURL* theURL = [NSURL fileURLWithPath:path];
AudioPlayer *audioPlayer = [[AudioPlayer alloc] initWithURL:theURL];

Resources