下面是代表音頻播放器文件的代碼。我正在試圖利用它在我的程序中播放聲音。我不想在每個視圖控制器中放置AVPlayer功能來播放可重複的聲音,所以我正在尋找一種方法將所有內容放在一個地方,並在需要時調用特定功能(音樂,點擊,介紹)使用不同的swift文件播放音頻
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
好吧,我擺脫了控制檯內的日誌是的,但它不能解決問題 –