Simple control of music playback and pauses with button

Source: Internet
Author: User

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

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.