• 在Swift3里面实现点击不同按钮播放不同声音的一种实现方法


    以下代码使用AVAudioPlayer(需要import AVFundation库并为相应的controller添加AVAudioPlayerDelegate,记得在viewDidLoad的时候还要把delegate设为self)

    import UIKit
    import AVFoundation

    class GameViewController: UIViewController, AVAudioPlayerDelegate {

    。。。。。。

    // declare a AVAudioPlayer object
    var audioPlayer: AVAudioPlayer?

    override func viewDidLoad() {
    super.viewDidLoad()

    // Set the delegate of AVAudioPlayer to self
    audioPlayer?.delegate = self

    // Play the first audio
    audioPlay(audioName: "end1")
    audioPlayer?.play()

    。。。。。。

    }

    @IBAction func btnMiddleClicked(_ sender: UIButton) {
    switch gameStep {
    case 0:


    // Set the audio
    audioPlay(audioName: "tianhei")
    // Play the audio
    audioPlayer?.play()
    gameStep += 1
    case 1:

    audioPlay(audioName: "jingzhang")
    // Play the audio
    audioPlayer?.play()
    // Set the timer
    self.timer = Timer.scheduledTimer(timeInterval: 1.0, target: self, selector: #selector(GameViewController.update), userInfo: nil, repeats: true)
    RunLoop.current.add(timer, forMode: RunLoopMode.commonModes)

    。。。。。。

    }

    // ----------------------------------------------------------
    // Audio Playing part

    func audioPlay(audioName: String) {
    let url = URL.init(fileURLWithPath: Bundle.main.path(forResource: audioName, ofType: "mp3")!)
    do {
    try audioPlayer = AVAudioPlayer(contentsOf: url)
    audioPlayer?.prepareToPlay()
    } catch {
    NSLog("Failed to set audio session category. Error: (error)")
    }
    }

    func audioPlayerDidFinishPlaying(_ player: AVAudioPlayer, successfully
    flag: Bool) {
    }

    func audioPlayerDecodeErrorDidOccur(_ player: AVAudioPlayer,
    error: Error?) {
    }

    func audioPlayerBeginInterruption(_ player: AVAudioPlayer) {
    }

    func audioPlayerEndInterruption(player: AVAudioPlayer) {
    }

    。。。。。。

    }

    另外这里需要提到一个比较严重的问题:

    在做项目的时候,我曾发现同样的代码在多台机器上会反复在播放声音的时候出错,而且没有任何错误提示。而在另外一些机器上却永远不出错。

    出错截屏如下:

    后来发现原因是部分Mac的音频输出没有设置成使用音频,而是用扬声器(speaker),这样就需要音频的比特率不得高于28kbps。

    而在另一些机器上,只要设置了是用音频,就可以正常播放。

    解决办法就是把我的mp3资源的比特率降到28kbps或以下。不过我现在选择就不管它了,因为手机上是可以播的,就是模拟器上可能会crash。无所谓

  • 相关阅读:
    关于VS2010出现“此方法显式使用的 CAS 策略已被 .NET Framework 弃用... ...请使用 NetFx40_LegacySecurityPolicy 配置开关”解决办法
    数据挖掘---Pandas的学习
    数据挖掘---Numpy的学习
    数据挖掘---Matplotib的学习
    AI学习---数据IO操作&神经网络基础
    AI学习---基于TensorFlow的案例[实现线性回归的训练]
    AI学习---卷积神经网络
    AI学习---数据读取&神经网络
    AI学习---TensorFlow框架介绍[图+会话+张量+变量OP+API]
    AI学习---深度学习&TensorFlow安装
  • 原文地址:https://www.cnblogs.com/guozai9527/p/6373066.html
Copyright © 2020-2023  润新知