Programmatically playing Audio in IOS

by / Monday, 26 August 2013 / Published in Ipad, Iphone

There are many ways in IOS to play an audio files.Such as System Sound Services, AVAudioPlayer, Audio Queue Services, and OpenAL.But the most popular and easy way to play an audio file is using AVAudioPlayer.Let’s learn the trick of how we can play sound files programmatically using AVAudioPlayer.

First of all we need to drag a sound file,which we want to play,in our project.Then we need to import the  AVFoundation framework from project library.Now in our controller file we will add an UIButton.In the button click we will play or pause the sound file as per our requirement.Now we need to declare an AVAudioPlayer type variable and a NSString type variable in our .h file and synthesize those in .m file.In .m file we ned to write following methods to play and pause the sound file respectively.

-(void)background_music{

NSURL *url = [NSURL fileURLWithPath:[NSString stringWithFormat:@"%@/backgroundtheme.mp3", [[NSBundle mainBundle] resourcePath]]];

NSError *error;

self.background_player = [[AVAudioPlayer alloc] initWithContentsOfURL:url error:&error];

self.background_player.numberOfLoops=-1;

if(error){

}

else{

[self.background_player play];

}

}

-(void)stop_music{

[self.background_player stop];

}

Now in button click we will manipulate the calls of theses two functions as per the value of the string variable which is initially set as “off” in viewDidLoad.

if([self.global_sound_str isEqualToString:@"off"]){

[manage_sound_btn setTitle:@"Pause" forState:UIControlStateNormal];

self.global_sound_str=@"on";

[self background_music];

}

else{

[manage_sound_btn setTitle:@"Play" forState:UIControlStateNormal];

self.global_sound_str=@"off";

[self stop_music];

}

 

TOP