下面是代表音频播放器文件的代码。我正在尝试利用它在我的程序中播放声音。我不想在每个视图控制器中放置AVPlayer功能来播放可重复的声音,因此我正在寻找一种方法将所有内容放在一个地方并在需要时调用特定功能(音乐,点击,介绍)
import UIKit
import AVFoundation
class player: UIViewController
{
var music:Bool = true
var sound:Bool = true
var intro:Bool = true
var soundPlayer: AVAudioPlayer?
var clickPlayer: AVAudioPlayer?
var musicPlayer : AVAudioPlayer?
{
get
{
let appDelegate = UIApplication.shared.delegate as! AppDelegate
return appDelegate.musicPlayer
}
set
{
let appDelegate = UIApplication.shared.delegate as! AppDelegate
appDelegate.musicPlayer = newValue
}
}
func playSound(title: String, format: String)
{
if sound == true
{
guard let url = Bundle.main.url(forResource: title, withExtension: format)
else { return }
do
{
try AVAudioSession.sharedInstance().setCategory(AVAudioSessionCategoryPlayback)
try AVAudioSession.sharedInstance().setActive(true)
soundPlayer = try AVAudioPlayer(contentsOf: url)
soundPlayer?.play()
}
catch let error
{
print(error.localizedDescription)
}
}
}
func playClick()
{
if sound == true
{
guard let url = Bundle.main.url(forResource: "click", withExtension: "mp3")
else { return }
do
{
try AVAudioSession.sharedInstance().setCategory(AVAudioSessionCategoryPlayback)
try AVAudioSession.sharedInstance().setActive(true)
let clickPlayer = try AVAudioPlayer(contentsOf: url)
clickPlayer.play()
}
catch let error
{
print(error.localizedDescription)
}
}
}
func playMusic()
{
if music == true
{
guard let url = Bundle.main.url(forResource: "ambientMusic", withExtension: "mp3")
else { return }
do
{
try AVAudioSession.sharedInstance().setCategory(AVAudioSessionCategoryPlayback)
try AVAudioSession.sharedInstance().setActive(true)
musicPlayer = try AVAudioPlayer(contentsOf: url)
musicPlayer?.play()
musicPlayer?.numberOfLoops = -1
}
catch let error
{
print(error.localizedDescription)
}
}
}
}
不同的档案:
@IBAction func play(_ sender: Any)
{
player().playClick()
performSegue(withIdentifier: "menuToIntro", sender: self)
}
但它没有发挥任何作用。只需打印日志 AQDefaultDevice(173):跳过输入流0 0 0x0
答案 0 :(得分:1)
从讨论here这是Xcode模拟器的一个错误,你应该尝试去编辑方案>运行>争论和 添加环境变量OS_ACTIVITY_MODE,值禁用。
答案 1 :(得分:1)
好的,发现了一个问题。在我的情况下,有必要将玩家存储为不会被销毁的财产或其他变量。这就是原因 - 声音播放但立即终止的原因。我通过在AppDelegate中声明AVAudioPlayers来修复它