iOS development-A simple introduction to audio playback and packaging tool classes

Source: Internet
Author: User
Tags local time

iOS development-A simple introduction to audio playback and packaging tool classes

First, the sound of the playback of a simple introduction

In simple terms, audio can be divided into 2 types

(1) Sound effects

Also known as "short audio", usually plays in the program for 1-2 seconds

Enhance the overall user experience with embellishment in the app

(2) Music

For example, the "background music" in the game, the general playing time is longer

Frame: Play audio needs to use avfoundation.framework frame

Second, the sound effects of playback

1. Get the path to the sound file

Nsurl *url = [[NSBundle mainbundle] urlforresource:@ "M_03.wav" withextension:nil];

2. Load the sound file to get the corresponding sound ID

Systemsoundid soundid = 0;

Audioservicescreatesystemsoundid (__bridge cfurlref) (URL), &soundid);

3. Play sound

Audioservicesplaysystemsound (Soundid);

Note: The audio file only needs to be loaded 1 times

4. Summary of common functions of sound playback

Loading sound files

Audioservicescreatesystemsoundid (Cfurlref infileurl, Systemsoundid *outsystemsoundid)

Releasing sound resources

Audioservicesdisposesystemsoundid (Systemsoundid Insystemsoundid)

Play sound

Audioservicesplaysystemsound (Systemsoundid Insystemsoundid)

Play sound with a little vibration

Audioservicesplayalertsound (Systemsoundid Insystemsoundid)

Iii. Examples of programs

First, import frameworks that need to be relied upon

Import sound file footage that needs to be played

Description: Converting something in the avfoundation.framework frame to CF requires the use of bridging.

Iv. Simple description of music playback

Music playback uses a class called Avaudioplayer, which can be used to play local music files on your phone.

Attention:

(1) This class (Avaudioplayer) can only be used to play local audio.

(2) shorter time (called sound effects) is created using Audioservicescreatesystemsoundid, while local time is longer (called music) using the Avaudioplayer class.

The Avaudioplayer class relies on the Avfoundation framework, so you must first import the Avfoundation framework and include its header file (including the primary header file) before using the class.

Note: A avaudioplayer can only play one URL, and if you want to play multiple files, you have to create multiple players.

VI. Play multiple Files

Click, URL, and press common to build a view.

It can be found that this URL is read-only and therefore can only be set by Initwithcontentsofurl, which means that only one audio file can be played by a player object.

So how do you play multiple audio files?

Consider encapsulating a tool class to play music

VII. Packaging audio file Playback tool class

Simple description

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.

Steps to implement the Encapsulation tool class:

Creates a new class that inherits from the NSObject class. Three external interfaces are available:

respectively:

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:

TXAudioTool.h file

//TXAudioTool.h//framework of the Liang////Created by Xin on 14/11/28.//Copyright (c) 2014 Liang. All rights reserved.////Play audio Tool class#import<Foundation/Foundation.h>#import<AVFoundation/AVFoundation.h>@interfaceTxaudiotool:nsobject/** * Play sound effects * * @param filename*/+ (void) PlaySound: (NSString *) filename;/** * Destroy sound effects * * @param filename*/+ (void) Disposesound: (NSString *) filename;/** * Play Music * * @param filename*/+ (Avaudioplayer *) Playmusic: (NSString *) filename;/** * Pause Music * * @param filename*/+ (void) Pausemusic: (NSString *) filename;/** * Stop music * * @param filename*/+ (void) Stopmusic: (NSString *) filename;/** * Returns the currently playing music player*/+ (Avaudioplayer *) Currentplayingaudioplayer;@end

TXAUDIOTOOL.M file

////TXAUDIOTOOL.M//framework of the Liang////Created by Xin on 14/11/28.//Copyright (c) 2014 Liang. All rights reserved.//Play audio Tool class#import "TXAudioTool.h"#import<AVFoundation/AVFoundation.h>@implementationTxaudiotool/** * Store all Audio IDs * Dictionary: FileName as key, soundid as value*/StaticNsmutabledictionary *_soundiddict;/** * Store All Music players * Dictionary: filename as key, audioplayer as value*/StaticNsmutabledictionary *_audioplayerdict;/** * Initialize*/+ (void) initialize{_soundiddict=[Nsmutabledictionary dictionary]; _audioplayerdict=[Nsmutabledictionary dictionary]; //set the audio session typeAvaudiosession *session =[Avaudiosession sharedinstance];    [Session Setcategory:avaudiosessioncategorysoloambient Error:nil]; [Session Setactive:yes Error:nil];}/** * Play sound effects * * @param filename*/+ (void) PlaySound: (NSString *) filename{if(!filename)return; //1. Remove the Soundid from the dictionarySystemsoundid Soundid =[_soundiddict[filename] unsignedlongvalue]; if(!soundid) {//Create//Loading sound filesNsurl *url =[[NSBundle Mainbundle] Urlforresource:filename Withextension:nil]; if(!url)return; //Create a sound IDAudioservicescreatesystemsoundid (__bridge cfurlref) URL, &Soundid); //put in a dictionary_soundiddict[filename] =@ (Soundid); }        //2. PlayAudioservicesplaysystemsound (Soundid);}/** * Destroy sound effects * * @param filename*/+ (void) Disposesound: (NSString *) filename{if(!filename)return; Systemsoundid Soundid=[_soundiddict[filename] unsignedlongvalue]; if(soundid) {//Destroy Sound IDAudioservicesdisposesystemsoundid (Soundid); //Remove from dictionary[_soundiddict Removeobjectforkey:filename]; }}/** * Play Music * * @param filename*/+ (Avaudioplayer *) Playmusic: (NSString *) filename{if(!filename)returnNil; //1. Remove the Audioplayer from the dictionaryAvaudioplayer *audioplayer =_audioplayerdict[filename]; if(!audioplayer) {//Create//Loading music filesNsurl *url =[[NSBundle Mainbundle] Urlforresource:filename Withextension:nil]; if(!url)returnNil; //Create AudioplayerAudioplayer =[[Avaudioplayer alloc] Initwithcontentsofurl:url Error:nil]; //Buffering[Audioplayer Preparetoplay]; //audioplayer.enablerate = YES; //audioplayer.rate = 10.0; //put in a dictionary_audioplayerdict[filename] =Audioplayer; }        //2. Playif(!audioplayer.isplaying) {[Audioplayer play]; }        returnAudioplayer;}/** * Pause Music * * @param filename*/+ (void) Pausemusic: (NSString *) filename{if(!filename)return; //1. Remove the Audioplayer from the dictionaryAvaudioplayer *audioplayer =_audioplayerdict[filename]; //2. Pause if(audioplayer.isplaying) {[Audioplayer pause]; }}/** * Stop music * * @param filename*/+ (void) Stopmusic: (NSString *) filename{if(!filename)return; //1. Remove the Audioplayer from the dictionaryAvaudioplayer *audioplayer =_audioplayerdict[filename]; //2. Pauseif(audioplayer.isplaying) {[Audioplayer stop]; //Direct Destruction[_audioplayerdict Removeobjectforkey:filename]; }}/** * Returns the currently playing music player*/+ (Avaudioplayer *) currentplayingaudioplayer{ for(NSString *filenameinch_audioplayerdict) {Avaudioplayer*audioplayer =_audioplayerdict[filename]; if(audioplayer.isplaying) {returnAudioplayer; }    }        returnNil;}@end

iOS development-A simple introduction to audio playback and packaging tool classes

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.