gpt4 book ai didi

swift - 使用不同的 swift 文件播放音频

转载 作者:搜寻专家 更新时间:2023-11-01 07:08:12 25 4
gpt4 key购买 nike

下面是表示音频播放器文件的代码。我正在尝试利用它在我的程序中播放声音。我不想在每个 View Controller 中放置一个 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): skipping input stream 0 0 0x0

最佳答案

来自讨论here这是 Xcode 模拟器的错误,您应该尝试去编辑方案 > 运行 > 参数和添加环境变量 OS_ACTIVITY_MODE,值禁用。

关于swift - 使用不同的 swift 文件播放音频,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46779038/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com