I am using AVAudioPlayer class to play audio but the problem is that when I play the audio I do not receive the callback in audioPlayerDidFinishPlaying when the file is finish playing and the file starts again even when the number of loops is set to 1
Here is the code.
.h
#interface AudioController : NSObject <AVAudioPlayerDelegate>
-(void) playBigGameTheme{
-(void) playMusic:(NSString*) fileName isLooping: (BOOL) isLooping;
#end
.m
#implementation AudioController{
AVAudioPlayer *audioPlayer;
}
-(void) playMusic:(NSString*) fileName isLooping: (BOOL) isLooping{
int loop = 1;
if(isLooping){
loop = -1;
}
[audioPlayer stop];
NSURL* soundUrl = [NSURL fileURLWithPath:[[NSBundle mainBundle] pathForResource:fileName ofType:#"mp3"]];
audioPlayer = [[AVAudioPlayer alloc] initWithContentsOfURL:soundUrl error:nil];
audioPlayer.numberOfLoops = loop;
[audioPlayer setDelegate:self];
NSLog(#"===Number of loops : %d", audioPlayer.numberOfLoops);
[audioPlayer play];
}
- (void) audioPlayerDidFinishPlaying:(AVAudioPlayer *)player successfully:(BOOL)flag
{
NSLog(#"HERE");
}
-(void) playBigGameTheme{
[self playMusic:BGAME_MAIN_MUSIC_FILE_NAME isLooping:NO];
}
#end
when I call playBigGameTheme the audio starts playing correctly. but it restarts when the sound is finished and when the audio finishes the second time then only the audioPlayerDidFinishPlaying method is called.
I am stuck and do not know whats going wrong..
even when the number of loops is set to 1
That's exactly why. The name and the behavior of this property is a bit counter-intuitive, but if you had read the documentation, it would have been clear that it sets the number of repetitions, and not the number of playbacks. Quote from the docs:
The value of 0, which is the default, means to play the sound once.
So set it to 0 (or don't set it, zero is the default value) and it will play the audio file only once:
audioPlayer.numberOfLoops = 0;
Related
I have an avaudioplayer that loads a sound file and loops. The problem is that everytime the file loops, there is a pause/delay which makes music sound bad.
I found this question which had a similar issue, but is for 2 players. I have a single player that has a 1 second pause at each loop: AVAudioPlayer eliminating one second pause between sound files
Here is what my audio player setup looks like:
#interface HomeViewController ()
#property (strong, nonatomic) DataController *dataController;
#end
#implementation HomeViewController
- (void)viewDidLoad {
[super viewDidLoad];
self.dataController = [DataController sharedInstance];
[self createAndStartAudioPlayer];
}
- (void) viewWillAppear:(BOOL)animated{
[self.dataController.player play];
}
- (void) createAndStartAudioPlayer {
NSTimeInterval shortStartDelay = 0.01; // seconds
NSTimeInterval now = self.dataController.player.deviceCurrentTime;
[self.dataController.player playAtTime: now + shortStartDelay];
NSString *soundFilePath = [[NSBundle mainBundle] pathForResource:#"jingle-loop" ofType:#"mp3"];
NSURL *soundFileURL = [NSURL fileURLWithPath:soundFilePath];
self.dataController.player = [[AVAudioPlayer alloc] initWithContentsOfURL:soundFileURL fileTypeHint:AVFileTypeMPEGLayer3 error:nil];
self.dataController.player.numberOfLoops = -1; //infinite
[self.dataController.player prepareToPlay];
}
How do I stop this 1 second pause and play the loop like it is a continuous song?
Mr. T in the comments was in fact right. The solution was to fix the white space that is added automatically by garage band.
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!
Hello my sounds play but if I keep hitting multiple sounds rapidly I get a crash EXC_BAD_ACCESS(code=1). Been trying for a long time to figure this one out. I tried using properties as well but no luck. Anybody ever seen this happen when playing multiple simultaneous sounds?
#interface SoundBoardScene : SKScene<AVAudioPlayerDelegate>
AVAudioPlayer *Player1;
AVAudioPlayer *Player2;
AVAudioPlayer *Player3;
AVAudioPlayer *Player4;
AVAudioPlayer *Player5;
AVAudioPlayer *Player6;
AVAudioPlayer *Player7;
AVAudioPlayer *Player8;
-(AVAudioPlayer*) PlayAudioFile:(AVAudioPlayer*)player withAudioFileName:(NSString*)audioFileName withExtensionType: (NSString*)audioFileExtension withLoopCount:(uint)NumberOfLoops
NSURL *url = [NSURL fileURLWithPath:[[NSBundle mainBundle]
pathForResource:audioFileName
ofType:audioFileExtension]];
player = [[AVAudioPlayer alloc] initWithContentsOfURL:url error:nil];
player.numberOfLoops = NumberOfLoops;
return player;
}
-(void) initSounds
Player1 = [animalObject PlayAudioFile:Player1 withAudioFileName:#"Sound1" withExtensionType:#"mp3" withLoopCount:0];
Player1.delegate=self;
Player2 = [animalObject PlayAudioFile:Player2 withAudioFileName:#"Sound2" withExtensionType:#"mp3" withLoopCount:0];
Player2.delegate=self;
etc
etc
}
if([node.name isEqualToString:#"Sound1"])
{
[Player1 play];
}
if([node.name isEqualToString:#"Sound2"])
{
[Player2 play];
}
there is no need to use avplayer for play sound file.
try this code
[self runAction:[SKAction repeatAction:[SKAction playSoundFileNamed:#"pew1.wav" waitForCompletion:NO] count:count]];
I'm writing an alarm clock app and I need to have the user select the chime to wake up to. I have a UITableView with a list of my sounds and when the user taps a sound I want it to play.
However, my sounds do not play unless I step over the call to AudioServicesPlaySystemSound (or if I put a breakpoint on the call to AudioServicesDisposeSystemSoundID which triggers after I hear the sound).
I had a theory that this was a main thread issue so I used performSelectorOnMainThread:
[self performSelectorOnMainThread:#selector(playWakeUpSound)
withObject:nil
waitUntilDone:true];
but that didn't help. (The value of waitUntilDone doesn't seem to matter.)
This question was promising but I checked and I'm only calling my method once.
This is only a guess, since I don't know what is in playWakeUpSound. If you are using AVAudioPlayer within that call and ARC, it might be because it is getting released. Store the instance of AVAudioPlayer as a member of the class and it should play.
#interface MyClass
{
AVAudioPlayer *player;
}
#end
Then in the implementation:
#implementation MyClass
- (void)playWakeUpSound {
// Assuming name and extension is set somewhere.
NSURL* musicFile = [NSURL fileURLWithPath:[[NSBundle mainBundle] pathForResource:name ofType:extension]];
NSError* error = nil;
player = [[AVAudioPlayer alloc] initWithContentsOfURL:musicFile error:&error];
if (error) {
NSLog(#"%#", error.localizedDescription);
} else {
[player play];
}
}
#end
I have 5 songs in my app that I would like to play one after the other with AVAudioPlayer.
Are there any examples of this? How can I accomplish this?
Any example code would be greatly appreciated!
Thanks!
AVQueuePlayer work for this situation.
AVQueuePlayer is a subclass of AVPlayer you use to play a number of items in sequence.
Instead of AVAudioPlayer you can use AVQueuePlayer which suits this use case better as suggested by Ken.
Here is a bit of code you can use:
#interface AVSound : NSObject
#property (nonatomic, retain) AVQueuePlayer* queuePlayer;
- (void)addToPlaylist:(NSString*)pathForResource ofType:(NSString*)ofType;
- (void)playQueue;
#end
#implementation AVSound
- (void)addToPlaylist:(NSString*)pathForResource ofType:(NSString*)ofType
{
// Path to the audio file
NSString *path = [[NSBundle mainBundle] pathForResource:pathForResource ofType:ofType];
// If we can access the file...
if ([[NSFileManager defaultManager] fileExistsAtPath:path])
{
AVPlayerItem *item = [[AVPlayerItem alloc] initWithURL:[NSURL fileURLWithPath:path]];
if (_queuePlayer == nil) {
_queuePlayer = [[AVQueuePlayer alloc] initWithPlayerItem:item];
}else{
[_queuePlayer insertItem:item afterItem:nil];
}
}
}
- (void)playQueue
{
[_queuePlayer play];
}
#end
Then to use it:
In your interface file:
#property (strong, nonatomic) AVSound *pageSound;
In your implementation file:
- (void)addAudio:(Book*)book pageNum:(int)pageNum
{
NSString *soundFileEven = [NSString stringWithFormat:#"%02d", pageNum-1];
NSString *soundPathEven = [NSString stringWithFormat:#"%#_%#", book.productId, soundFileEven];
NSString *soundFileOdd = [NSString stringWithFormat:#"%02d", pageNum];
NSString *soundPathOdd = [NSString stringWithFormat:#"%#_%#", book.productId, soundFileOdd];
if (_pageSound == nil) {
_pageSound = [[AVSound alloc]init];
_pageSound.player.volume = 0.5;
}
[_pageSound clearQueue];
[_pageSound addToPlaylist:soundPathEven ofType:#"mp3"];
[_pageSound addToPlaylist:soundPathOdd ofType:#"mp3"];
[_pageSound playQueue];
}
HTH
For every song you want to make make a single AVPlayer.
NSURL *url = [NSURL URLWithString:pathToYourFile];
AVPlayer *audioPlayer = [[AVPlayer alloc] initWithURL:url];
[audioPlayer play];
You can get a Notification when the player ends. Check AVPlayerItemDidPlayToEndTimeNotification when setting up the player:
audioPlayer.actionAtItemEnd = AVPlayerActionAtItemEndNone;
[[NSNotificationCenter defaultCenter] addObserver:self
selector:#selector(playerItemDidReachEnd:)
name:AVPlayerItemDidPlayToEndTimeNotification
object:[audioPlayer currentItem]];
this will prevent the player to pause at the end.
in the notification:
- (void)playerItemDidReachEnd:(NSNotification *)notification
{
// start your next song here
}
You can start your next song as soon as you get a notification that the current playing song is done. Maintain some counter which is persistent across selector calls. That way using counter % [songs count] will give you an infinite looping playlist :)
Don't forget un unregister the notification when releasing the player.
Unfortunately, AVAudioPlayer can only play one file. To play two files, you have to kill the first instance of the AVAudioPlayer and recreate it a second time (it can be initiated using - (id)initWithContentsOfURL:(NSURL *)url error:(NSError **)outError). The problem with this approach is that there is a slight delay between when the first file finishes playing and when the second file starts playing. If you want to get rid of this delay you have to dig into Core Audio and come up with a much more complex solution.