播放音频(资源文件)

先将资源文件添加到工程中,如下代码为播放代码
class ViewController: UIViewController {
override func viewDidLoad() {
    super.viewDidLoad()
    // Do any additional setup after loading the view, typically from a nib.
}

//MARK:- 音效播放

override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
    print("开始播放音效")
    //1.获取systemSoundId:Creates a system sound object.
    let url =  Bundle.main.url(forResource: "m_17.wav", withExtension: nil)
    let urlCF = url! as CFURL
    //1.1 创建SystemSoundId
    var soundID : SystemSoundID = 0
    AudioServicesCreateSystemSoundID(urlCF, &soundID)
    //2.根据soundId,播放音效
      //带有震动播放效果
  // AudioServicesPlayAlertSound(soundID)
      //不带有震动播放
//AudioServicesPlaySystemSound(soundID)
   //带有回调函数的播放
    AudioServicesPlaySystemSoundWithCompletion(soundID) {
        //3.根据soundId,释放音效
        print("根据soundId,释放音效")
        AudioServicesDisposeSystemSoundID(soundID)
    }
 }
    override func touchesEnded(_ touches: Set<UITouch>, with event: UIEvent?) {
    print("结束播放音效")
}
}
封装后的音频播放方法
//  Audio_Extension.swift
import UIKit
import AVFoundation

//类方法
class AudioTool: NSObject {
class func audioPlay(audioName:String,isAlert:Bool,inCompletion:@escaping ()->()){
//1.获取systemSoundId:Creates a system sound object.
let url =  Bundle.main.url(forResource: audioName, withExtension: nil)
let urlCF = url! as CFURL
//1.1 创建SystemSoundId
var soundID : SystemSoundID = 0
AudioServicesCreateSystemSoundID(urlCF, &soundID)
//2.根据soundId,播放音效
    if isAlert {
        AudioServicesPlayAlertSoundWithCompletion(soundID) {
            //3. 根据soundId,释放音效
            AudioServicesDisposeSystemSoundID(soundID)
            //4.告诉外界播放完成的事件
            inCompletion()
        }
    }else {
        AudioServicesPlaySystemSoundWithCompletion(soundID) {
            //3.根据soundId,释放音效
            AudioServicesDisposeSystemSoundID(soundID)
            //4.告诉外界播放完成的事件
            inCompletion()
        }
        
    }
 }
}
外界调用
override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
    print("开始播放音效")
    AudioTool.audioPlay(audioName: "m_17.wav", isAlert: false) {
        print("成功释放")
    }
}
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • Android 自定义View的各种姿势1 Activity的显示之ViewRootImpl详解 Activity...
    passiontim阅读 175,062评论 25 709
  • 用两张图告诉你,为什么你的 App 会卡顿? - Android - 掘金 Cover 有什么料? 从这篇文章中你...
    hw1212阅读 14,467评论 2 59
  • 1、通过CocoaPods安装项目名称项目信息 AFNetworking网络请求组件 FMDB本地数据库组件 SD...
    阳明AI阅读 16,038评论 3 119
  • 为了提高孩子们的阅读写作能力,同时为中考作好准备,我们同时进行名著阅读活动,自9月16日开始,每天读16—20页,...
    绿塬阅读 1,085评论 0 0
  • 2017年7月22星期六 晴 今天女儿去书法学习班试课啦!上午的舞蹈课美术课,加上下午的书法课,一天的时间...
    厦小薛智一爸爸阅读 1,878评论 0 5