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