iOS Development extension-Package audio file Playback Tool class

Source: Internet
Author: User

iOS Development extension-Package audio file Playback Tool class

A simple explanation

1. A brief description of music playback

(1) music plays with a class called Avaudioplayer

(2) Common methods of Avaudioplayer

Loading music files

-(ID) Initwithcontentsofurl: (nsurl *) URL error: (nserror * *) Outerror;

-(ID) Initwithdata: (NSData *) Data error: (NSERROR * *) Outerror;

Ready to play (buffer, improve the smoothness of playback)-(BOOL) Preparetoplay;

Play (asynchronous play)-(BOOL) play;

Pause-(void) pause;

Stop-(void) stop;

Is playing @property (ReadOnly, getter=isplaying) BOOL playing;

Duration @property (readonly) nstimeinterval duration;

The current playback bit @property nstimeinterval currenttime;

Play Count (-1 for Infinite loop playback, other representatives play numberofloops+1 times @property Nsinteger numberofloops;

Volume @property float volume;

Whether to allow rate change @property BOOL enablerate;

The playback rate (1 is the normal rate, 0.5 is the general rate, and 2 is double) @property float rate;

The number of channels @property (readonly) Nsuinteger numberofchannels;

2. Play multiple music files

Note: If you want to play multiple music files, then the most foolish thing is to create multiple global players to play the corresponding music files, but this method does not apply to the number of files that need to play a huge amount of cases.

Another approach is to encapsulate a tool class that plays music files. Wrapper tool class implementation step: Create a new class that inherits from the NSObject class. Provides three external interfaces: Play Music (Parameters: file name, return value: BOOL) Pause Music (parameter: file name) Stop music (parameter: file name) The code in the tool class is designed as follows: YYAudioTool.h file
1//2//  YYAudioTool.h 3//  17-playback of multiple music files 4//5//  Created by Apple on 14-8-9.6//  Copyright (c) 2014 y Angyong. All rights reserved. 7//8  9 #import <foundation/foundation.h>10 #import <avfoundation/avfoundation.h>11 @interface Yyaudiotool:nsobject12/**13  * Play music file  */15 + (BOOL) Playmusic: (NSString *) filename;16/**17  * Pause Playback 18  */19 + (void) Pausemusic: (NSString *) filename;20/**21  * Play music file  + */23 + (void) Stopmusic: (NSString *) Filename;24 @end

YYAUDIOTOOL.M file

 1//2//YYAUDIOTOOL.M 3//17-playback of multiple music files 4//5//Created by Apple on 14-8-9. 6//Copyright (c) 2014 Yangyong. All rights reserved.  7//8 9 #import "YYAudioTool.h" @implementation YYAudioTool12/**13 * Store All Music players */15 Static nsmutabledictionary *_musices;16 + (Nsmutabledictionary *) musices17 {if (_musices==nil) {_musices=[nsmutabledictionary dicti Onary];20}21 return _musices;22}23 24/**25 * Play Music */27 + (BOOL) Playmusic: (NSString *) Filename28 {if (!     FileName) return no;//returns 30//1 if no file name is passed in. Remove the corresponding player Avaudioplayer *player=[self musices][filename];32 33 2. If the player is not created, initialize the!player {35//2.1 audio file URL36 nsurl *url=[[nsbundle Mainbundle]urlforre         Source:filename withextension:nil];37 if (!url) return no;//if the URL is empty, then return directly 38 39//2.2 create player 40 Player=[[avaudioplayer Alloc]initwithcontentsofurl:url error:nil];41 42//2.3 Buffered if (![ Player PREPARetoplay]) return no;//If the buffer fails, then return directly 44 45//2.4 to the dictionary [self musices][filename]=player;47}48 49//3. Play if (![ Player IsPlaying]) {51//If it is not currently playing, then play the [player play];53}54 return yes;//is playing, then return Back YES56}57 + (void) Pausemusic: (NSString *) filename59 {if (!filename) return;//If no file name is passed in, the 61 62//1 is returned directly. Remove the corresponding player Avaudioplayer *player=[self musices][filename];64 65//2. Pause [Player pause];//if Palyer is empty, that is equivalent to [ Nil pause], so there's no need to do the processing.}69 + (void) Stopmusic: (NSString *) filename71 {if (!filename) return;//If no file name is passed in, then directly Returns 73 74//1. Remove the corresponding player Avaudioplayer *player=[self musices][filename];76 77//2. Stop [player stop] ; 79 80//3 Remove the player from the dictionary [[self musices] removeobjectforkey:filename];82}83 @end

Test procedure:

Drag and drop the controls in the storyboard and connect them to control.

Import the music footage that is available for playback.

The code of the test program is designed as follows:

 1//2//YYVIEWCONTROLLER.M 3//17-playback of multiple music files 4//5//Created by Apple on 14-8-9. 6//Copyright (c) 2014 Yangyong. All rights reserved.  7//8 9 #import "YYViewController.h" #import "YYAudioTool.h" one @interface Yyviewcontroller ()-(ibaction) play;14 -(Ibaction) pause;15-(ibaction) stop;16-(ibaction) next;17 18//Use an array to save All music files @property (Nonatomic,strong) Nsarray *SONGS;20//Use an int type property to record the current index @property (nonatomic,assign) int currentindex;22 @end23 @implementation YYViewController25 #pragma mark-lazy load-(Nsarray *) songs27 {if (_songs==nil) {email protected][@ "23 5319.mp3 ", @" 309769.mp3 ", @" 120125029.mp3 "];30}31 return _songs;32}33-(void) viewDidLoad35 {$ [Super view]  didload];37}38-(ibaction) Play {40//Start play/continue to play [Yyaudiotool playmusic:self.songs[self.currentindex]];42}43 -(ibaction) Pause {45//Pause Play [Yyaudiotool pausemusic:self.songs[self.currentindex]];47}48-(ibaction) St OP {50//Stop playback 51 [yyaudiotool stopmusic:self.songs[self.currentindex]];52}53 54//Play Next first-(ibaction) Next {56//1. Stop the current play 57 first         [Self stop];58 59//2. Set Current index +160 self.currentindex++;61 if (self.currentindex>=self.songs.count) {62 self.currentindex=0;63}64 65//3. Play Music [self play];67}68 @end

Second, the tool class to transform, so that it can play audio files

Description

Sound only creates, plays, and destroys (stops) three operations because the sound effects are generally short, so there is no way to pause.

  

Add the playback of the sound file to the tool class, implementing the following code:

YYAudioTool.h file

1//2//  YYAudioTool.h 3//  17-playback of multiple music files 4//5//  Created by Apple on 14-8-9.6//  Copyright (c) 2014 y Angyong. All rights reserved. 7//8  9 #import <foundation/foundation.h>10 #import <avfoundation/avfoundation.h>11 @interface Yyaudiotool:nsobject12/**13  * Play music file  */15 + (BOOL) Playmusic: (NSString *) filename;16/**17  * Pause Playback 18  */19 + (void) Pausemusic: (NSString *) filename;20/**21  * Play music file  + */23 + (void) Stopmusic: (NSString *) Filename;24/**26  * Play audio file  */28 + (void) PlaySound: (NSString *) filename;29/**30  * Destroy sound effects  */32 + (void) Disposesound: (NSString *) filename;33 @end

YYAUDIOTOOL.M file

  1//2//YYAUDIOTOOL.M 3//17-playback of multiple music files 4//5//Created by Apple on 14-8-9. 6//Copyright (c) 2014 Yangyong.  All rights reserved. 7//8 9 #import "YYAudioTool.h" @implementation yyaudiotool 12/** 13 * Store All Music players */static Nsmutabledi Ctionary *_musicplayers; + (Nsmutabledictionary *) musicplayers (_musicplayers==nil) {_musicplayers=[nsmutabledictionar Y dictionary]; return _musicplayers; 22} 23 24/** 25 * Store all the sound effects ID */static nsmutabledictionary *_soundids; + (Nsmutabledictionary *) Soundids {if (_soundids==nil) {_soundids=[nsmutabledictionary dictionary ]; _soundids return; 34} 35 36 37/** 38 * Play Music * */+ (BOOL) Playmusic: (NSString *) filename (!filename) return no;//if not passed Enter the file name, then directly return 43//1. Remove the corresponding player Avaudioplayer *player=[self musicplayers][filename]; 45 46//2. If the player is not created, initialize the IF (!player) {48//2.1 toneURL of the frequency file Nsurl *url=[[nsbundle mainbundle]urlforresource:filename Withextension:nil]; if (!url) return no;//if the URL is empty, then return directly 51 52//2.2 create player Player=[[avaudioplayer Alloc] Initwithcontentsofurl:url Error:nil]; 54 55//2.3 Buffered if (![ Player Preparetoplay]) return no;//If the buffer fails, then return directly 57 58//2.4 to the dictionary (self musicplayers][filename ]=player; 60} 61 62//3. Play if (![ Player IsPlaying]) {64//If it is not currently playing, then play [player play];      , then return yes to + (void) Pausemusic: (NSString *) filename (!filename) return;//If the file name is not passed in, it returns 74 directly 75//1. Remove the corresponding player Avaudioplayer *player=[self musicplayers][filename]; 77 78//2. Pause [player pause];//] If the palyer is empty, that is equivalent to [nil pause], so there is no need to do the processing of the "Bayi" + (void) Stopmusic: (NSS Tring *) filename (!filename) return;//returns 86 if no file name is passed in      87//1. Remove the corresponding player Avaudioplayer *player=[self musicplayers][filename]; 89 90//2. Stop [player stop]; 92 93//3 Remove the player from the dictionary 94 [[Self musicplayers] removeobjectforkey:filename]; 95} 96 97//Play sound 98 + (void) PlaySound: (NSString *) filename (!filename) return;101//1. Remove the corresponding sound effects 102 S Ystemsoundid soundid=[[self Soundids][filename] unsignedintegervalue];103 104//2. Play Sound 105//2.1 If the sound ID does not exist, create 106 if (!soundid) {107 108//audio file URL109 nsurl *url=[[nsbundle Mainbundle]urlforresource:filen Ame withextension:nil];110 if (!url) return;//if the URL does not exist, then return directly 111 osstatus status = Audioservi         Cescreatesystemsoundid ((__bridge cfurlref) (URL), &soundid), 113 NSLog (@ "%ld", status); 114//Deposit in Dictionary 115 [Self soundids] [FileName] [Email protected] (Soundid); 116}117 118//2.2 with sound ID, play sound effects 119 audioservicesplaysystemsound (Soundid); 120}121 122//Destroy Sound 123 + (void) Disposesound: (NSString *) filename124 {125//If the incoming file name is empty, then return directly 126 if (!filename) return;127 128// 1. Remove the corresponding sound 129 systemsoundid soundid=[[self Soundids][filename] unsignedintegervalue];130 131//2. Destroy the  Soundid) {133 audioservicesdisposesystemsoundid (Soundid); 134 135//2.1 Remove 136 from the dictionary after it is destroyed [[self soundids]removeobjectforkey:filename];137}138}139 @end

Code test:

Code Description:

The printed value is 0 and plays successfully (because the function is in C + +)

iOS Development extension-Package audio file Playback Tool class

Related Article

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.