仿【知乎】tabBar点击时有声音特效

版本:swift3.0

声音类型:wav
调用方法: {
依赖库: AudioToolbox

   //soundID给文件一个ID,用来确定调用那个音频文件
   var soundID:SystemSoundID = 0
   //将ZH_TS.wav文件拖入工程中,通过bundle导入
    let soundPath = Bundle.main.path(forResource: "ZH_TS", ofType: "wav")
    //解包,防止崩溃soundPath是可选型
    if soundPath == nil {
        print("无效的wav声音文件")
    }else{
   //将音频文件转换成URL
    let baseURL = NSURL(fileURLWithPath: soundPath!)
    //注册:将URL和soundID传给播放器
    AudioServicesCreateSystemSoundID(baseURL, &soundID)
    //播放
    AudioServicesPlaySystemSound(soundID)           

}

声音类型:m4a
调用方法: {
依赖库: AVFoundation

      var player = AVAudioPlayer() //这一定要定义成全局变量
      do {      //AVAudioPlayer会抛出异常,采用do-catch操作
    let soundPath = Bundle.main.path(forResource:           "ZH_FollowClick", ofType: "m4a")
        if soundPath == nil {
            print("此m4a文件无效")
        }else{
     //生成data对象
      let data = NSData.init(contentsOfFile: soundPath!)
      player = try AVAudioPlayer.init(data: data! as Data)
      player.numberOfLoops = 1
      player.volume = 1.0
      player.play()     
        }
    }
     catch{
        print("error:\(error)")
        }    

}

【知乎tabBar点击后嘟嘟嘟的响实现方法】:
调用tabBarcontroller的方法:
override func tabBar(_ tabBar: UITabBar, didSelect item: UITabBarItem) {
在此方法中 调用你想用的声音文件
}

你可能感兴趣的:(仿【知乎】tabBar点击时有声音特效)