zoukankan      html  css  js  c++  java
  • 在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。无所谓

  • 相关阅读:
    DOS命令
    vim学习
    Python学习笔记小结之猜数字游戏
    Python学习笔记函数之异常处理
    Python学习笔记函数之global语句
    Python学习笔记函数之局部和全局作用域
    Python学习笔记函数之关键字参数和print()
    Python学习笔记函数之None值
    Python学习笔记函数之返回值和return语句
    Python学习笔记函数之def语句和参数
  • 原文地址:https://www.cnblogs.com/guozai9527/p/6373066.html
Copyright © 2011-2022 走看看