How to play multiple audio files in a row with AVAudioPlayer? - ios

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.

Related

ios remove avaudioplayer loop delay

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.

AVAudioPlayer not playing long sounds?

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!

AVAudioPlayer crashes my app with EXC_BAD_ACCESS(code=1) when running multiple sounds at once

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]];

How to play tracks from iPod music library with different volume than system volume?

How can I play music from the ipod music library (like user-defined playlists, etc.) at a different volume than the system volume?
This is for anyone who is trying to play music / playlists from the ipod music library at a different volume than the system volume. There are several posts out there saying that the [MPMusicPlayerController applicationMusicPlayer] can do this, but I have found that anytime I change the volume of the applicationMusicPlayer, the system volume changes too.
There is a more involved method of playing music using the AVAudioPlayer class, but it requires you to copy music files from the ipod library to the application bundle, and that can get tricky when you're playing dynamic things, like user generated playlists. That technique does give you access to the bytes though, and is the way to go if you want to do processing on the data (like a DJ app). Link to that solution HERE.
The solution I went with uses the AVPlayer class, there are several good posts out there about how to do it. This post is basically a composite of several different solutions I found on Stackoverflow and elsewhere.
I have the following Frameworks linked:
AVFoundation
MediaPlayer
AudioToolbox
CoreAudio
CoreMedia
(I'm not sure if all of those are critical, but that's what I have. I have some OpenAL stuff implemented too that I don't show in the following code)
// Presumably in your SoundManage.m file (or whatever you call it) ...
#import <CoreAudio/CoreAudioTypes.h>
#import <AudioToolbox/AudioToolbox.h>
#interface SoundManager()
#property (retain, nonatomic) AVPlayer* audioPlayer;
#property (retain, nonatomic) AVPlayerItem* currentItem;
#property (retain, nonatomic) MPMediaItemCollection* currentPlaylist;
#property (retain, nonatomic) MPMediaItem* currentTrack;
#property (assign, nonatomic) MPMusicPlaybackState currentPlaybackState;
#end
#implementation SoundManager
#synthesize audioPlayer;
#synthesize currentItem = m_currentItem;
#synthesize currentPlaylist;
#synthesize currentTrack;
#synthesize currentPlaybackState;
- (id) init
{
...
//Define an AVPlayer instance
AVPlayer* tempPlayer = [[AVPlayer alloc] init];
self.audioPlayer = tempPlayer;
[tempPlayer release];
...
//load the playlist you want to play
MPMediaItemCollection* playlist = [self getPlaylistWithName: #"emo-pop-unicorn-blood-rage-mix-to-the-max"];
if(playlist)
[self loadPlaylist: playlist];
...
//initialize the playback state
self.currentPlaybackState = MPMusicPlaybackStateStopped;
//start the music playing
[self playMusic];
...
}
//Have a way to get a playlist reference (as an MPMediaItemCollection in this case)
- (MPMediaItemCollection*) getPlaylistWithName:(NSString *)playlistName
{
MPMediaQuery* query = [[MPMediaQuery alloc] init];
MPMediaPropertyPredicate* mediaTypePredicate = [MPMediaPropertyPredicate predicateWithValue: [NSNumber numberWithInteger: MPMediaTypeMusic] forProperty:MPMediaItemPropertyMediaType];
[query addFilterPredicate: mediaTypePredicate];
[query setGroupingType: MPMediaGroupingPlaylist];
NSArray* playlists = [query collections];
[query release];
for(MPMediaItemCollection* testPlaylist in playlists)
{
NSString* testPlaylistName = [testPlaylist valueForProperty: MPMediaPlaylistPropertyName];
if([testPlaylistName isEqualToString: playlistName])
return testPlaylist;
}
return nil;
}
//Override the setter on currentItem so that you can add/remove
//the notification listener that will tell you when the song has completed
- (void) setCurrentItem:(AVPlayerItem *)currentItem
{
if(m_currentItem)
{
[[NSNotificationCenter defaultCenter] removeObserver:self name:AVPlayerItemDidPlayToEndTimeNotification object:m_currentItem];
[m_currentItem release];
}
if(currentItem)
m_currentItem = [currentItem retain];
else
m_currentItem = nil;
if(m_currentItem)
{
[[NSNotificationCenter defaultCenter] addObserver:self selector:#selector(handleMusicTrackFinished) name:AVPlayerItemDidPlayToEndTimeNotification object:m_currentItem];
}
}
//handler that gets called when the name:AVPlayerItemDidPlayToEndTimeNotification notification fires
- (void) handleMusicTrackFinished
{
[self skipSongForward]; //or something similar
}
//Have a way to load a playlist
- (void) loadPlaylist:(MPMediaItemCollection *)playlist
{
self.currentPlaylist = playlist;
self.currentTrack = [playlist.items objectAtIndex: 0];
}
//Play the beats, yo
- (void) playMusic
{
//check the current playback state and exit early if we're already playing something
if(self.currentPlaybackState == MPMusicPlaybackStatePlaying)
return;
if(self.currentPlaybackState == MPMusicPlaybackStatePaused)
{
[self.audioPlayer play];
}
else if(self.currentTrack)
{
//Get the system url of the current track, and use that to make an AVAsset object
NSURL* url = [self.currentTrack valueForProperty:MPMediaItemPropertyAssetURL];
AVAsset* asset = [AVURLAsset URLAssetWithURL:url options:nil];
//Get the track object from the asset object - we'll need to trackID to tell the
//AVPlayer that it needs to modify the volume of this track
AVAssetTrack* track = [[asset tracksWithMediaType:AVMediaTypeAudio] objectAtIndex:0];
//Build the AVPlayerItem - this is where you modify the volume, etc. Not the AVPlayer itself
AVPlayerItem* playerItem = [[AVPlayerItem alloc] initWithAsset: asset]; //initWithURL:url];
self.currentItem = playerItem;
//Set up some audio mix parameters to tell the AVPlayer what to do with this AVPlayerItem
AVMutableAudioMixInputParameters* audioParams = [AVMutableAudioMixInputParameters audioMixInputParameters];
[audioParams setVolume: 0.5 atTime:kCMTimeZero]; //replace 0.5 with your volume
[audioParams setTrackID: track.trackID]; //here's the track id
//Set up the actual AVAudioMix object, which aggregates effects
AVMutableAudioMix* audioMix = [AVMutableAudioMix audioMix];
[audioMix setInputParameters: [NSArray arrayWithObject: audioParams]];
//apply your AVAudioMix object to the AVPlayerItem
[playerItem setAudioMix:audioMix];
//refresh the AVPlayer object, and play the track
[self.audioPlayer replaceCurrentItemWithPlayerItem: playerItem];
[self.audioPlayer play];
}
self.currentPlaybackState = MPMusicPlaybackStatePlaying;
}
- (void) pauseMusic
{
if(self.currentPlaybackState == MPMusicPlaybackStatePaused)
return;
[self.audioPlayer pause];
self.currentPlaybackState = MPMusicPlaybackStatePaused;
}
- (void) skipSongForward
{
//adjust self.currentTrack to be the next object in self.currentPlaylist
//start the new track in a manner similar to that used in -playMusic
}
- (void) skipSongBackward
{
float currentTime = self.audioPlayer.currentItem.currentTime.value / self.audioPlayer.currentItem.currentTime.timescale;
//if we're more than a second into the song, just skip back to the beginning of the current track
if(currentTime > 1.0)
{
[self.audioPlayer seekToTime: CMTimeMake(0, 1)];
}
else
{
//otherwise, adjust self.currentTrack to be the previous object in self.currentPlaylist
//start the new track in a manner similar to that used in -playMusic
}
}
//Set volume mid-song - more or less the same process we used in -playMusic
- (void) setMusicVolume:(float)vol
{
AVPlayerItem* item = self.audioPlayer.currentItem;
AVAssetTrack* track = [[item.asset tracksWithMediaType:AVMediaTypeAudio] objectAtIndex:0];
AVMutableAudioMixInputParameters* audioParams = [AVMutableAudioMixInputParameters audioMixInputParameters];
[audioParams setVolume: vol atTime:kCMTimeZero];
[audioParams setTrackID: track.trackID];
AVMutableAudioMix* audioMix = [AVMutableAudioMix audioMix];
[audioMix setInputParameters: [NSArray arrayWithObject: audioParams]];
[item setAudioMix:audioMix];
}
#end
Please forgive any errors you see - let me know in the comments and I'll fix them. Otherwise, I hope this helps if anyone runs into the same challenge I did!
Actually I found a really easy way to do this by loading iPod URL's from MPMusicPlayer, but then doing playback through AVAudioPlayer.
// Get-da iTunes player thing
MPMusicPlayerController* iTunes = [MPMusicPlayerController iPodMusicPlayer];
// whazzong
MPMediaItem *currentSong = [iTunes nowPlayingItem];
// whazzurl
NSURL *currentSongURL = [currentSong valueForProperty:MPMediaItemPropertyAssetURL];
info( "AVAudioPlayer playing %s", [currentSongURL.absoluteString UTF8String] ) ;
// mamme AVAudioPlayer
NSError *err;
avAudioPlayer = [[AVAudioPlayer alloc] initWithContentsOfURL:currentSongURL error:&err] ;
if( err!=nil )
{
error( "AVAudioPlayer couldn't load %s", [currentSongURL.absoluteString UTF8String] ) ;
}
avAudioPlayer.numberOfLoops = -1; //infinite
// Play that t
[avAudioPlayer prepareToPlay] ;
[avAudioPlayer play];
[avAudioPlayer setVolume:0.5]; // set the AVAUDIO PLAYER's volume to only 50%. This
// does NOT affect system volume. You can adjust this music volume anywhere else too.

AVAudioPlayer audioPlayerDidFinishPlaying called when the file is played second time

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;

Resources