ViewController.h
Define a button
@property (strong,nonatomic) UIButton *button;
Viewcontroller.m
#import "ViewController.h"
Import Header File
#import <AVFoundation/AVFoundation.h>
@interface Viewcontroller ()
Defining the properties of a player
@property (Nonatomic,strong) Avaudioplayer *player;
@end
@implementation Viewcontroller
-(void) Viewdidload {
[Super Viewdidload];
Get the full path to the MP3 file
NSString *musicfiledpath=[[nsbundle Mainbundle] pathforresource:@ "Andy Lau-Ice Rain" oftype:@ "MP3"];
Also gets the path
Nsurl *musicurl=[[nsurl alloc] Initfileurlwithpath:musicfiledpath];
Create an object named Theplay
Avaudioplayer *theplay=[[avaudioplayer alloc] Initwithcontentsofurl:musicurl Error:nil];
Set the location of the button
Self.button=[[uibutton Alloc] Initwithframe:cgrectmake (150, 150, 100, 50)];
Name of the button
[Self.button settitle:@ "Play + pause" forstate:uicontrolstatenormal];
Background color of the button
Self.button.backgroundcolor=[uicolor Graycolor];
[Self.view AddSubview:self.button];
Responding to playback events
[Self.button addtarget:self Action: @selector (Testplayer) forcontrolevents:uicontroleventtouchupinside];
Create player
Self.player=theplay;
}
-(void) Testplayer
{
if (self.button.tag==0)
{
Pre-play
[Self.player Preparetoplay];
Set the number of times the music plays, 1 for loop playback
Self.player.numberofloops=-1;
Play
[Self.player play];
self.button.tag=1;
}
Else
{
[Self.player stop];
self.button.tag=0;
}
}
-(void) didreceivememorywarning {
[Super didreceivememorywarning];
Dispose of any resources the can be recreated.
}
@end
Simple control of music playback and pauses with button