Kai*_*rne 15 avfoundation avaudioplayer ios swift
我正在尝试在AVAudioPlayer实例上播放多个声音文件,但是当播放一个声音时,另一个声音停止播放.我不能一次播放多个声音.这是我的代码:
import AVFoundation
class GSAudio{
static var instance: GSAudio!
var soundFileNameURL: NSURL = NSURL()
var soundFileName = ""
var soundPlay = AVAudioPlayer()
func playSound (soundFile: String){
GSAudio.instance = self
soundFileName = soundFile
soundFileNameURL = NSURL(fileURLWithPath: NSBundle.mainBundle().pathForResource(soundFileName, ofType: "aif", inDirectory:"Sounds")!)
do{
try soundPlay = AVAudioPlayer(contentsOfURL: soundFileNameURL)
} catch {
print("Could not play sound file!")
}
soundPlay.prepareToPlay()
soundPlay.play ()
}
}
Run Code Online (Sandbox Code Playgroud)
任何人都可以通过告诉我如何一次播放多个声音文件来帮助我吗?任何帮助深表感谢.
非常感谢,凯
Oli*_*son 23
音频停止的原因是因为您只设置了一个AVAudioPlayer,所以当您要求该类播放另一个声音时,您正在使用新的AVAudioPlayer实例替换旧实例.你基本上都在覆盖它.
您可以创建GSAudio类的两个实例,然后在每个实例上调用playSound,或者使该类成为使用audioPlayers字典的通用音频管理器.
我更喜欢后一种选择,因为它允许更清晰的代码,也更有效.您可以检查以前是否已经为声音制作了播放器,而不是制作新的播放器.
无论如何,我为你重新上课,这样它就能同时播放多个声音.它也可以播放相同的声音(它不会取代以前的声音实例)希望它有所帮助!
该类是单例,因此要访问该类使用:
GSAudio.sharedInstance
Run Code Online (Sandbox Code Playgroud)
例如,播放您要调用的声音:
GSAudio.sharedInstance.playSound("AudioFileName")
Run Code Online (Sandbox Code Playgroud)
并立刻播放一些声音:
GSAudio.sharedInstance.playSounds("AudioFileName1", "AudioFileName2")
Run Code Online (Sandbox Code Playgroud)
或者您可以在某个地方加载数组中的声音并调用接受数组的playSounds函数:
let sounds = ["AudioFileName1", "AudioFileName2"]
GSAudio.sharedInstance.playSounds(sounds)
Run Code Online (Sandbox Code Playgroud)
我还添加了一个playSounds函数,它允许您以级联的格式延迟播放的每个声音.所以:
let soundFileNames = ["SoundFileName1", "SoundFileName2", "SoundFileName3"]
GSAudio.sharedInstance.playSounds(soundFileNames, withDelay: 1.0)
Run Code Online (Sandbox Code Playgroud)
会在sound1之后播放sound2,然后sound3会在sound2之后播放一秒钟等.
这是班级:
class GSAudio: NSObject, AVAudioPlayerDelegate {
static let sharedInstance = GSAudio()
private override init() {}
var players = [NSURL:AVAudioPlayer]()
var duplicatePlayers = [AVAudioPlayer]()
func playSound (soundFileName: String){
let soundFileNameURL = NSURL(fileURLWithPath: NSBundle.mainBundle().pathForResource(soundFileName, ofType: "aif", inDirectory:"Sounds")!)
if let player = players[soundFileNameURL] { //player for sound has been found
if player.playing == false { //player is not in use, so use that one
player.prepareToPlay()
player.play()
} else { // player is in use, create a new, duplicate, player and use that instead
let duplicatePlayer = try! AVAudioPlayer(contentsOfURL: soundFileNameURL)
//use 'try!' because we know the URL worked before.
duplicatePlayer.delegate = self
//assign delegate for duplicatePlayer so delegate can remove the duplicate once it's stopped playing
duplicatePlayers.append(duplicatePlayer)
//add duplicate to array so it doesn't get removed from memory before finishing
duplicatePlayer.prepareToPlay()
duplicatePlayer.play()
}
} else { //player has not been found, create a new player with the URL if possible
do{
let player = try AVAudioPlayer(contentsOfURL: soundFileNameURL)
players[soundFileNameURL] = player
player.prepareToPlay()
player.play()
} catch {
print("Could not play sound file!")
}
}
}
func playSounds(soundFileNames: [String]){
for soundFileName in soundFileNames {
playSound(soundFileName)
}
}
func playSounds(soundFileNames: String...){
for soundFileName in soundFileNames {
playSound(soundFileName)
}
}
func playSounds(soundFileNames: [String], withDelay: Double) { //withDelay is in seconds
for (index, soundFileName) in soundFileNames.enumerate() {
let delay = withDelay*Double(index)
let _ = NSTimer.scheduledTimerWithTimeInterval(delay, target: self, selector: #selector(playSoundNotification(_:)), userInfo: ["fileName":soundFileName], repeats: false)
}
}
func playSoundNotification(notification: NSNotification) {
if let soundFileName = notification.userInfo?["fileName"] as? String {
playSound(soundFileName)
}
}
func audioPlayerDidFinishPlaying(player: AVAudioPlayer, successfully flag: Bool) {
duplicatePlayers.removeAtIndex(duplicatePlayers.indexOf(player)!)
//Remove the duplicate player once it is done
}
}
Run Code Online (Sandbox Code Playgroud)
我创建了一个帮助程序库,可以简化在 Swift 中播放声音的过程。它创建了 AVAudioPlayer 的多个实例以允许同时多次播放相同的声音。你可以从 Github 下载它或者用 Cocoapods 导入。
这是链接:SwiftySound
用法很简单:
Sound.play(file: "sound.mp3")
Run Code Online (Sandbox Code Playgroud)
这是@Oliver Wilkinson代码的Swift 4版本,具有一些安全检查和改进的代码格式:
import Foundation
import AVFoundation
class GSAudio: NSObject, AVAudioPlayerDelegate {
static let sharedInstance = GSAudio()
private override init() { }
var players: [URL: AVAudioPlayer] = [:]
var duplicatePlayers: [AVAudioPlayer] = []
func playSound(soundFileName: String) {
guard let bundle = Bundle.main.path(forResource: soundFileName, ofType: "aac") else { return }
let soundFileNameURL = URL(fileURLWithPath: bundle)
if let player = players[soundFileNameURL] { //player for sound has been found
if !player.isPlaying { //player is not in use, so use that one
player.prepareToPlay()
player.play()
} else { // player is in use, create a new, duplicate, player and use that instead
do {
let duplicatePlayer = try AVAudioPlayer(contentsOf: soundFileNameURL)
duplicatePlayer.delegate = self
//assign delegate for duplicatePlayer so delegate can remove the duplicate once it's stopped playing
duplicatePlayers.append(duplicatePlayer)
//add duplicate to array so it doesn't get removed from memory before finishing
duplicatePlayer.prepareToPlay()
duplicatePlayer.play()
} catch let error {
print(error.localizedDescription)
}
}
} else { //player has not been found, create a new player with the URL if possible
do {
let player = try AVAudioPlayer(contentsOf: soundFileNameURL)
players[soundFileNameURL] = player
player.prepareToPlay()
player.play()
} catch let error {
print(error.localizedDescription)
}
}
}
func playSounds(soundFileNames: [String]) {
for soundFileName in soundFileNames {
playSound(soundFileName: soundFileName)
}
}
func playSounds(soundFileNames: String...) {
for soundFileName in soundFileNames {
playSound(soundFileName: soundFileName)
}
}
func playSounds(soundFileNames: [String], withDelay: Double) { //withDelay is in seconds
for (index, soundFileName) in soundFileNames.enumerated() {
let delay = withDelay * Double(index)
let _ = Timer.scheduledTimer(timeInterval: delay, target: self, selector: #selector(playSoundNotification(_:)), userInfo: ["fileName": soundFileName], repeats: false)
}
}
@objc func playSoundNotification(_ notification: NSNotification) {
if let soundFileName = notification.userInfo?["fileName"] as? String {
playSound(soundFileName: soundFileName)
}
}
func audioPlayerDidFinishPlaying(_ player: AVAudioPlayer, successfully flag: Bool) {
if let index = duplicatePlayers.index(of: player) {
duplicatePlayers.remove(at: index)
}
}
}
Run Code Online (Sandbox Code Playgroud)
所有的答案都是张贴代码页;它不需要那么复杂。
// Create a new player for the sound; it doesn't matter which sound file this is
let soundPlayer = try AVAudioPlayer( contentsOf: url )
soundPlayer.numberOfLoops = 0
soundPlayer.volume = 1
soundPlayer.play()
soundPlayers.append( soundPlayer )
// In an timer based loop or other callback such as display link, prune out players that are done, thus deallocating them
checkSfx: for player in soundPlayers {
if player.isPlaying { continue } else {
if let index = soundPlayers.index(of: player) {
soundPlayers.remove(at: index)
break checkSfx
}
}
}
Run Code Online (Sandbox Code Playgroud)
我通常在整个项目中避免松散的字符串,而是使用自定义协议来保存这些字符串属性的对象。
与这种方法相比,我更喜欢这种enum方法,因为枚举往往会很快地将您的项目结合在一起。每次添加新案例时,您都必须使用枚举编辑同一文件,这在一定程度上打破了 SOLID 的开闭原则,并增加了出错的机会。
在这种特殊情况下,您可以有一个定义声音的协议:
protocol Sound {
func getFileName() -> String
func getFileExtension() -> String
func getVolume() -> Float
func isLoop() -> Bool
}
extension Sound {
func getVolume() -> Float { 1 }
func isLoop() -> Bool { false }
}
Run Code Online (Sandbox Code Playgroud)
当您需要新的声音时,您可以简单地创建一个实现此协议的新结构或类(如果您的 IDE(就像 Xcode 一样)支持它,甚至会在自动完成上建议它,从而为您提供与枚举类似的好处。 .并且它在中型到大型多框架项目中效果更好)。
(通常我将卷和其他配置保留为默认实现,因为它们不太频繁定制)。
例如,您可以听到硬币掉落的声音:
protocol Sound {
func getFileName() -> String
func getFileExtension() -> String
func getVolume() -> Float
func isLoop() -> Bool
}
extension Sound {
func getVolume() -> Float { 1 }
func isLoop() -> Bool { false }
}
Run Code Online (Sandbox Code Playgroud)
然后,您可以使用一个单例SoundManager来负责管理播放音频文件
struct CoinDropSound: Sound {
func getFileName() -> String { "coin_drop" }
func getFileExtension() -> String { "wav" }
}
Run Code Online (Sandbox Code Playgroud)
在这里,我创建了一个帮助程序getAudioPlayer,以便能够从代码执行中尽早返回并利用guard let.
guard let大多数时候,更频繁地使用并减少嵌套代码可以极大地提高可读性。
要从项目中的任何位置使用它SoundManager,只需访问其共享实例并传递一个符合Sound.
例如,考虑到前面的CoinDropSound:
import AVFAudio
final class SoundManager: NSObject, AVAudioPlayerDelegate {
static let shared = SoundManager()
private var audioPlayers: [URL: AVAudioPlayer] = [:]
private var duplicateAudioPlayers: [AVAudioPlayer] = []
private override init() {}
func play(sound: Sound) {
let fileName = sound.getFileName()
let fileExtension = sound.getFileExtension()
guard let url = Bundle.main.url(forResource: fileName, withExtension: fileExtension),
let player = getAudioPlayer(for: url) else { return }
player.volume = sound.getVolume()
player.numberOfLoops = numberOfLoops
player.prepareToPlay()
player.play()
}
private func getAudioPlayer(for url: URL) -> AVAudioPlayer? {
guard let player = audioPlayers[url] else {
let player = try? AVAudioPlayer(contentsOf: url)
audioPlayers[url] = player
return player
}
guard player.isPlaying else { return player }
guard let duplicatePlayer = try? AVAudioPlayer(contentsOf: url) else { return nil }
duplicatePlayer.delegate = self
duplicateAudioPlayers.append(duplicatePlayer)
return duplicatePlayer
}
func audioPlayerDidFinishPlaying(_ player: AVAudioPlayer, successfully flag: Bool) {
duplicateAudioPlayers.removeAll { $0 == player }
}
}
Run Code Online (Sandbox Code Playgroud)
您可以省略该sound参数,因为它可以提高可读性
class SoundManager {
// ...
func play(_ sound: Sound) {
// ...
}
// ...
}
Run Code Online (Sandbox Code Playgroud)
进而:
SoundManager.shared.play(CoinDropSound())
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
9640 次 |
| 最近记录: |