幾種播放音頻文件的方式(二) —— 音效播放

版本記錄

版本號 時間
V1.0 2017.12.26

前言

ios系統(tǒng)中有很多方式可以播放音頻文件锰什,這里我們就詳細的說明下播放音樂文件的原理和實例。感興趣的可以看我寫的上面幾篇可都。
1. 幾種播放音頻文件的方式(一) —— 播放本地音樂

功能需求

音效播放忘渔,音頻文件必須打包成.caf编整、.aif、.wav中的一種元镀。有時候有的mp3格式的聲音文件也能播放绍填,而且API限制了時間不能超過30s。


功能實現(xiàn)

這里同樣使用框架 #import <AudioToolbox/AudioToolbox.h>

1. 幾個函數(shù)說明

由于該框架是基于C的框架栖疑,這里使用了其中的幾個函數(shù)讨永,下面我們就解析一下。

創(chuàng)建音效的ID遇革,音效的播放和銷毀都靠這個ID來執(zhí)行卿闹。

  • AudioServicesCreateSystemSoundID(CFURLRef inFileURL, SystemSoundID* outSystemSoundID)
/*!
    @functiongroup  AudioServices
*/

/*!
    @function       AudioServicesCreateSystemSoundID
    @abstract       Allows the application to designate an audio file for playback by the System Sound server.
    @discussion     Returned SystemSoundIDs are passed to AudioServicesPlayAlertSoundWithCompletion() 
                    and AudioServicesPlaySystemSoundWithCompletion() to be played.
 
                    The maximum supported duration for a system sound is 30 secs.
    @param          inFileURL
                        A CFURLRef for an AudioFile.
    @param          outSystemSoundID
                        Returns a SystemSoundID.
*/
extern OSStatus 
AudioServicesCreateSystemSoundID(   CFURLRef                    inFileURL,
                                    SystemSoundID*              outSystemSoundID)
                                                                __OSX_AVAILABLE_STARTING(__MAC_10_5,__IPHONE_2_0);

30s的音效限制就是在這里說明的。

播放音效

  • AudioServicesPlaySystemSound(SystemSoundID inSystemSoundID)
/*!
    This function will be deprecated in a future release. Use AudioServicesPlaySystemSoundWithCompletion instead.
 
    @function       AudioServicesPlaySystemSound
    @abstract       Play the sound designated by the provided SystemSoundID.
    @discussion     A SystemSoundID indicating the desired System Sound to be played.
    @param          inSystemSoundID
                        A SystemSoundID for the System Sound server to play.
*/
extern void 
AudioServicesPlaySystemSound(SystemSoundID inSystemSoundID)                                         
                                                                __OSX_AVAILABLE_STARTING(__MAC_10_5,__IPHONE_2_0);

銷毀音效的播放

  • AudioServicesDisposeSystemSoundID(SystemSoundID inSystemSoundID)
/*!
    @function       AudioServicesDisposeSystemSoundID
    @abstract       Allows the System Sound server to dispose any resources needed for the provided
                    SystemSoundID.
    @discussion     Allows the application to tell the System Sound server that the resources for the
                    associated audio file are no longer required.
    @param          inSystemSoundID
                        A SystemSoundID that the application no longer needs to use.
*/
extern OSStatus 
AudioServicesDisposeSystemSoundID(SystemSoundID inSystemSoundID)                                    
                                                                __OSX_AVAILABLE_STARTING(__MAC_10_5,__IPHONE_2_0);

ios9以前判斷音效的完成

  • AudioServicesAddSystemSoundCompletion(SystemSoundID inSystemSoundID,CFRunLoopRef __nullable inRunLoop, CFStringRef __nullable inRunLoopMode,AudioServicesSystemSoundCompletionProc inCompletionRoutine,void * __nullable inClientData)
/*!
    This function will be deprecated in a future release. Use AudioServicesPlayAlertSoundWithCompletion 
    or AudioServicesPlaySystemSoundWithCompletion instead.
 
    @function       AudioServicesAddSystemSoundCompletion
    @abstract       Call the provided Completion Routine when provided SystemSoundID
                    finishes playing.
    @discussion     Once set, the System Sound server will send a message to the System Sound client
                    indicating which SystemSoundID has finished playing.
    @param          inSystemSoundID
                        The SystemSoundID to associate with the provided completion
                        routine.
    @param          inRunLoop
                        A CFRunLoopRef indicating the desired run loop the completion routine should
                        be run on. Pass NULL to use the main run loop.
    @param          inRunLoopMode
                        A CFStringRef indicating the run loop mode for the runloop where the
                        completion routine will be executed. Pass NULL to use kCFRunLoopDefaultMode.
    @param          inCompletionRoutine
                        An AudioServicesSystemSoundCompletionProc to be called when the provided
                        SystemSoundID has completed playing in the server.
    @param          inClientData
                        A void* to pass client data to the completion routine.
*/
extern OSStatus 
AudioServicesAddSystemSoundCompletion(  SystemSoundID                                       inSystemSoundID,
                                        CFRunLoopRef __nullable                             inRunLoop,
                                        CFStringRef __nullable                              inRunLoopMode,
                                        AudioServicesSystemSoundCompletionProc              inCompletionRoutine,
                                        void * __nullable                                   inClientData)
                                                                    __OSX_AVAILABLE_STARTING(__MAC_10_5,__IPHONE_2_0);

ios9及其以后判斷音效的完成

  • AudioServicesPlayAlertSoundWithCompletion( SystemSoundID inSystemSoundID,void (^__nullable inCompletionBlock)(void))

/*!
    @function       AudioServicesPlayAlertSoundWithCompletion
    @abstract       Play an alert sound
    @discussion     Play the sound designated by the provided SystemSoundID with alert sound behavior.
    @param          inSystemSoundID
                        The SystemSoundID to be played. On the desktop the kSystemSoundID_UserPreferredAlert
                        constant can be passed in to play back the alert sound selected by the user
                        in System Preferences. On iOS there is no preferred user alert sound.
    @param          inCompletionBlock
                        The completion block gets executed for every attempt to play a system sound irrespective
                        of success or failure. The callbacks are issued on a serial queue and the client is
                        responsible for handling thread safety.
*/
extern void
AudioServicesPlayAlertSoundWithCompletion(  SystemSoundID inSystemSoundID,
                                            void (^__nullable inCompletionBlock)(void))
                                                                    __OSX_AVAILABLE_STARTING(__MAC_10_11, __IPHONE_9_0);
  • AudioServicesPlaySystemSoundWithCompletion(SystemSoundID inSystemSoundID, void (^__nullable inCompletionBlock)(void))
/*!
    @function       AudioServicesPlaySystemSoundWithCompletion
    @abstract       Play a system sound
    @discussion     Play the sound designated by the provided SystemSoundID.
    @param          inSystemSoundID
                        The SystemSoundID to be played.
    @param          inCompletionBlock
                        The completion block gets executed for every attempt to play a system sound irrespective 
                        of success or failure. The callbacks are issued on a serial queue and the client is 
                        responsible for handling thread safety.
*/
extern void
AudioServicesPlaySystemSoundWithCompletion(     SystemSoundID inSystemSoundID,
                                                void (^__nullable inCompletionBlock)(void))
                                                                        __OSX_AVAILABLE_STARTING(__MAC_10_11, __IPHONE_9_0);

帶有震動的播放

  • AudioServicesPlayAlertSound(SystemSoundID inSystemSoundID)
/*!
    This function will be deprecated in a future release. Use AudioServicesPlayAlertSoundWithCompletion instead.
 
    @function       AudioServicesPlayAlertSound
    @abstract       Play an Alert Sound
    @discussion     Play the provided SystemSoundID with AlertSound behavior.
    @param          inSystemSoundID
                        A SystemSoundID for the System Sound server to play. On the desktop you
                        can pass the kSystemSoundID_UserPreferredAlert constant to playback the alert sound 
                        selected by the user in System Preferences. On iOS there is no preferred user alert sound.
*/
extern void 
AudioServicesPlayAlertSound(SystemSoundID inSystemSoundID)                                          
                                                                __OSX_AVAILABLE_STARTING(__MAC_10_5,__IPHONE_2_0);

2. 代碼實現(xiàn)

下面直接看代碼

#import "ViewController.h"
#import <AudioToolbox/AudioToolbox.h>

@interface ViewController ()

@end

@implementation ViewController

static SystemSoundID soundID = 0;

#pragma mark -  Override Base Function

- (void)viewDidLoad
{
    [super viewDidLoad];
    
    self.view.backgroundColor = [UIColor whiteColor];
    
    //UI界面
    [self initUI];
}

#pragma mark -  Object Private Function

void soundCompleteCallBack(SystemSoundID soundID, void * clientDate)
{
    NSLog(@"播放完成");
    AudioServicesDisposeSystemSoundID(soundID);
}

- (void)playMusic
{
    //獲取資源地址
    NSString *str = [[NSBundle mainBundle] pathForResource:@"sound" ofType:@"m4a"];
    NSURL *url = [NSURL fileURLWithPath:str];
    
    // 創(chuàng)建音效的ID萝快,音效的播放和銷毀都靠這個ID來執(zhí)行
    AudioServicesCreateSystemSoundID((__bridge CFURLRef _Nonnull)(url), &soundID);
    
    //帶有聲音和震動的播放
    if ([UIDevice currentDevice].systemVersion.floatValue >= 9.0) {
        AudioServicesPlayAlertSoundWithCompletion(soundID, ^{
            NSLog(@"播放完成");
        });
    }
    else {
        AudioServicesAddSystemSoundCompletion(soundID, NULL, NULL, soundCompleteCallBack, NULL);
    };
}

- (void)stopMusic
{
    AudioServicesDisposeSystemSoundID(soundID);
}

- (void)initUI
{
    UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
    button.frame = CGRectMake((self.view.bounds.size.width - 200.0) * 0.5, (self.view.bounds.size.height - 200.0) * 0.5, 200.0, 200.0);
    button.backgroundColor = [UIColor lightGrayColor];
    button.layer.cornerRadius = 100.0;
    button.layer.masksToBounds = YES;
    [button setTitle:@"開始播放" forState:UIControlStateNormal];
    [button setTitle:@"停止播放" forState:UIControlStateSelected];
    [button setTitleColor:[UIColor blueColor] forState:UIControlStateNormal];
    [button setTitleColor:[UIColor blueColor] forState:UIControlStateSelected];
    [button addTarget:self action:@selector(playButtonDidClick:) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:button];
}

#pragma mark -  Action && Notification

- (void)playButtonDidClick:(UIButton *)button
{
    button.selected = !button.selected;
    
    if (button.selected) {
        [self playMusic];
    }
    else {
        [self stopMusic];
    }
}

@end

這里是播放聲音的同時锻霎,AudioServicesPlayAlertSoundWithCompletion,也有震動揪漩。


功能驗證

這里帶有聲音和震動旋恼,我就沒辦法給大家驗證了,只能給出一個基本的界面奄容。

開始播放
停止播放

后記

未完冰更,待續(xù)~~~

?著作權歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
  • 序言:七十年代末,一起剝皮案震驚了整個濱河市昂勒,隨后出現(xiàn)的幾起案子蜀细,更是在濱河造成了極大的恐慌,老刑警劉巖戈盈,帶你破解...
    沈念sama閱讀 216,470評論 6 501
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件审葬,死亡現(xiàn)場離奇詭異,居然都是意外死亡奕谭,警方通過查閱死者的電腦和手機涣觉,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 92,393評論 3 392
  • 文/潘曉璐 我一進店門,熙熙樓的掌柜王于貴愁眉苦臉地迎上來血柳,“玉大人官册,你說我怎么就攤上這事∧寻疲” “怎么了膝宁?”我有些...
    開封第一講書人閱讀 162,577評論 0 353
  • 文/不壞的土叔 我叫張陵鸦难,是天一觀的道長。 經(jīng)常有香客問我员淫,道長合蔽,這世上最難降的妖魔是什么? 我笑而不...
    開封第一講書人閱讀 58,176評論 1 292
  • 正文 為了忘掉前任介返,我火速辦了婚禮拴事,結(jié)果婚禮上,老公的妹妹穿的比我還像新娘圣蝎。我一直安慰自己刃宵,他們只是感情好,可當我...
    茶點故事閱讀 67,189評論 6 388
  • 文/花漫 我一把揭開白布徘公。 她就那樣靜靜地躺著牲证,像睡著了一般。 火紅的嫁衣襯著肌膚如雪关面。 梳的紋絲不亂的頭發(fā)上坦袍,一...
    開封第一講書人閱讀 51,155評論 1 299
  • 那天,我揣著相機與錄音等太,去河邊找鬼捂齐。 笑死,一個胖子當著我的面吹牛澈驼,可吹牛的內(nèi)容都是我干的辛燥。 我是一名探鬼主播,決...
    沈念sama閱讀 40,041評論 3 418
  • 文/蒼蘭香墨 我猛地睜開眼缝其,長吁一口氣:“原來是場噩夢啊……” “哼挎塌!你這毒婦竟也來了?” 一聲冷哼從身側(cè)響起内边,我...
    開封第一講書人閱讀 38,903評論 0 274
  • 序言:老撾萬榮一對情侶失蹤榴都,失蹤者是張志新(化名)和其女友劉穎,沒想到半個月后漠其,有當?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體嘴高,經(jīng)...
    沈念sama閱讀 45,319評論 1 310
  • 正文 獨居荒郊野嶺守林人離奇死亡,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點故事閱讀 37,539評論 2 332
  • 正文 我和宋清朗相戀三年和屎,在試婚紗的時候發(fā)現(xiàn)自己被綠了拴驮。 大學時的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片。...
    茶點故事閱讀 39,703評論 1 348
  • 序言:一個原本活蹦亂跳的男人離奇死亡柴信,死狀恐怖套啤,靈堂內(nèi)的尸體忽然破棺而出,到底是詐尸還是另有隱情随常,我是刑警寧澤潜沦,帶...
    沈念sama閱讀 35,417評論 5 343
  • 正文 年R本政府宣布萄涯,位于F島的核電站,受9級特大地震影響唆鸡,放射性物質(zhì)發(fā)生泄漏涝影。R本人自食惡果不足惜,卻給世界環(huán)境...
    茶點故事閱讀 41,013評論 3 325
  • 文/蒙蒙 一争占、第九天 我趴在偏房一處隱蔽的房頂上張望燃逻。 院中可真熱鬧,春花似錦燃乍、人聲如沸唆樊。這莊子的主人今日做“春日...
    開封第一講書人閱讀 31,664評論 0 22
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽。三九已至嘿辟,卻和暖如春舆瘪,著一層夾襖步出監(jiān)牢的瞬間,已是汗流浹背红伦。 一陣腳步聲響...
    開封第一講書人閱讀 32,818評論 1 269
  • 我被黑心中介騙來泰國打工英古, 沒想到剛下飛機就差點兒被人妖公主榨干…… 1. 我叫王不留,地道東北人昙读。 一個月前我還...
    沈念sama閱讀 47,711評論 2 368
  • 正文 我出身青樓召调,卻偏偏與公主長得像,于是被迫代替她去往敵國和親蛮浑。 傳聞我的和親對象是個殘疾皇子唠叛,可洞房花燭夜當晚...
    茶點故事閱讀 44,601評論 2 353

推薦閱讀更多精彩內(nèi)容