AUDIO PLAYER in Objective-C
An audio can be played in iOS app using class AVAudioPlayer that provides playback of audio data from a file or memory.
(Using Xcode 8 for iOS 10)
Follow the below steps to build an Audio playing App:
Step 1: Create a Single View Application
Next, enter product name as AudioPlayerDemo and select language as Objective-C.
Step 2: Firstly, add any audio file into the project by simply drag and drop method (make sure below selected option on RHS image should be checked).
Step 3: Now, just go to main.storyboard and set a button named Play Audio onto the controller.
Also, set property of Action connection for the Play Audio button.
Step 4: Go to ViewController.h file and import AVFoundation Framework. Also create instance variable of AVAudioPlayer.
Code will look like:-
#import <UIKit/UIKit.h>
#import <AVFoundation/AVFoundation.h>
@interface ViewController: UIViewController
{
AVAudioPlayer *audioPlayer;
}
-(IBAction) playAudio: (id)sender;
Step 5: In ViewController.m file, type the below code in the curly braces of button method.
NSString *path = [[NSBundle mainBundle] pathForResource:@"audio" ofType:@"mp3"];
NSURL *url = [NSURL fileURLWithPath: path];
audioPlayer = [[AVAudioPlayer alloc] initWithContentsOfURL: path error: NULL];
[audioPlayer play];
[audioPlayer play];
Code will look like:-
#import "ViewController.h"
@interface ViewController ()
@end
@implementation ViewController
- (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.
}
-(IBAction)playAudio:(id)sender{
NSString *path = [[NSBundle mainBundle]
pathForResource:@"audio" ofType:@"mp3"];
audioPlayer = [[AVAudioPlayer alloc]initWithContentsOfURL:
[NSURL fileURLWithPath:path] error:NULL];
[audioPlayer play];
}
@end
Step 6: Run the App
Enjoy Music 😇
Visit below link for watching video of the above mentioned blog:
https://www.youtube.com/watch?v=mYDWk3Oq3tg
Visit below link for watching video of the above mentioned blog:
https://www.youtube.com/watch?v=mYDWk3Oq3tg
If this will be helpful to u all, plz share your review on comment.
ReplyDeleteThanks
This blog is so helpful to me....plz share more ideas
ReplyDeleteMr. Ranjit Kumar, definitely I will share more & more for you all.
DeleteThanks Mr. Mukesh for your helpful blogs for me...
ReplyDeleteAlways welcome Mr. Ankit !
DeleteIam not able to get the output sound
ReplyDeleteMr. Prath!
DeleteEither your laptop sound might be on mute or your might have not checked the mark while importing that audio file.
you can watch my video on the same subject, link mentioned below:
https://www.youtube.com/watch?v=mYDWk3Oq3tg&index=17&list=UUA9bucG42cWEXBLCLNd-BmQ
Iam not able to get the output sound
ReplyDeleteGive link for GitHub project
ReplyDelete