设为首页 加入收藏

TOP

在Swift3里面实现点击不同按钮播放不同声音的一种实现方法
2017-10-10 12:13:44 】 浏览:4713
Tags: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。无所谓

】【打印繁体】【投稿】【收藏】 【推荐】【举报】【评论】 【关闭】 【返回顶部
上一篇如何在Swift3中获取Json包的内容.. 下一篇Swift3.0 三级联动UIPickerView城..

最新文章

热门文章

Hot 文章

Python

C 语言

C++基础

大数据基础

linux编程基础

C/C++面试题目