iOS開發拓展篇—音效的播放

來源:互聯網
上載者:User

標籤:

iOS開發拓展篇—音效的播放

一、簡單介紹

簡單來說,音頻可以分為2種

(1)音效

又稱“短音頻”,通常在程式中的播放時間長度為1~2秒

在應用程式中起到點綴效果,提升整體使用者體驗

(2)音樂

  比如遊戲中的“背景音樂”,一般播放時間較長

架構:播放音頻需要用到AVFoundation.framework架構

 

二、音效的播放

1.獲得音效檔案的路徑

  NSURL *url = [[NSBundle mainBundle] URLForResource:@"m_03.wav" withExtension:nil];

2.載入音效檔案,得到對應的音效ID

  SystemSoundID soundID = 0;

  AudioServicesCreateSystemSoundID((__bridge CFURLRef)(url), &soundID);

3.播放音效

  AudioServicesPlaySystemSound(soundID);

 

注意:音效檔案只需要載入1次

4.音效播放常見函數總結

載入音效檔案

  AudioServicesCreateSystemSoundID(CFURLRef inFileURL, SystemSoundID *outSystemSoundID)

釋放音效資源

  AudioServicesDisposeSystemSoundID(SystemSoundID inSystemSoundID)

播放音效

  AudioServicesPlaySystemSound(SystemSoundID inSystemSoundID)

播放音效帶點震動

  AudioServicesPlayAlertSound(SystemSoundID inSystemSoundID)

 

三、程式樣本

先匯入需要依賴的架構

匯入需要播放的音效檔案素材

  

說明:AVFoundation.framework架構中的東西轉換為CF需要使用橋接。

程式碼範例:

YYViewController.m檔案

 1 // 2 //  YYViewController.m 3 //  14-音效播放 4 // 5 //  Created by apple on 14-8-8. 6 //  Copyright (c) 2014年 yangyong. All rights reserved. 7 // 8  9 #import "YYViewController.h"10 #import <AVFoundation/AVFoundation.h>11 12 @interface YYViewController ()13 14 @end15 16 @implementation YYViewController17 18 - (void)viewDidLoad19 {20     [super viewDidLoad];21 }22 23 -(void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event24 {25     //1.獲得音效檔案的全路徑26     27     NSURL *url=[[NSBundle mainBundle]URLForResource:@"buyao.wav" withExtension:nil];28     29     //2.載入音效檔案,建立音效ID(SoundID,一個ID對應一個音效檔案)30     SystemSoundID soundID=0;31     AudioServicesCreateSystemSoundID((__bridge CFURLRef)url, &soundID);32     33     //把需要銷毀的音效檔案的ID傳遞給它既可銷毀34     //AudioServicesDisposeSystemSoundID(soundID);35     36     //3.播放音效檔案37     //下面的兩個函數都可以用來播放音效檔案,第一個函數伴隨有震動效果38     AudioServicesPlayAlertSound(soundID);39     //AudioServicesPlaySystemSound(<#SystemSoundID inSystemSoundID#>)40 }41 42 @end

說明:點擊螢幕可以播放音效檔案。

 

  

iOS開發拓展篇—音效的播放

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

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.