基本上,我使用swift,最新版本在xcode中制作这个应用程序,问题在于:
override func viewDidLoad() {
super.viewDidLoad()
Sound.play(file: "bensound-summer", fileExtension: "mp3", numberOfLoops: -1)
我正在使用带有pod的第三方库,名为" SwiftySound"。它用于通过应用程序播放音频。
我的目标是让我的应用中的背景音乐在无限循环中自动播放(以上代码代表的内容)
但问题是,当我点击我的按钮进入另一个视图控制器,然后我回去时,它会在上一个循环的顶部再次重放,因此两个音频文件同时播放。我希望它能够与所有视图控制器保持一致。
下载所有内容:
import UIKit
import AVFoundation
import SpriteKit
import SwiftySound
var Clicks = Int()
class ViewController: UIViewController {
@IBOutlet weak var LabelClicks: UILabel!
@IBAction func Button(_ sender: Any) {
Clicks+=1
LabelClicks.text="\(Clicks)" + " Clicks!"
UserDefaults.standard.set(LabelClicks.text, forKey: "clicks")
UserDefaults.standard.set(Clicks, forKey: "amount")
}
override func viewDidAppear(_ animated: Bool) {
if let x = UserDefaults.standard.object(forKey: "amount") as? Int {
Clicks = x
}
if let y = UserDefaults.standard.object(forKey: "clicks") as? String {
self.LabelClicks.text = y
}
}
@IBAction func UpgradeButton(_ sender: Any) {
performSegue(withIdentifier: "segue", sender: self)
}
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
let UpgradesController = segue.destination as! UpgradesViewController
UpgradesController.clickString = LabelClicks.text!
}
override func viewDidLoad() {
super.viewDidLoad()
Sound.play(file: "bensound-summer", fileExtension: "mp3", numberOfLoops: -1)
// Do any additional setup after loading the view, typically from a nib.
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
答案 0 :(得分:0)
在AppDelegate
' didFinishedLaunchingWithOptions
如下:
class AppDelegate: UIResponder, UIApplicationDelegate {
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
// Override point for customization after application launch.
Sound.play(file: "bensound-summer", fileExtension: "mp3", numberOfLoops: -1)
return true
}
}
如果您想在应用程序变为背景时停止声音,并在前景中再次播放,则可以采取以下方法:
func applicationDidBecomeActive(_ application: UIApplication) {
// Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
Sound.play(file: "bensound-summer", fileExtension: "mp3", numberOfLoops: -1)
}
func applicationWillResignActive(_ application: UIApplication) {
// Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
// Use this method to pause ongoing tasks, disable timers, and invalidate graphics rendering callbacks. Games should use this method to pause the game.
Sound.stopAll()
}