在 Swift Xcode 中达到 'Insert Background Music' 的简单方法
Easy way to 'Insert Background Music' in Swift Xcode
我的声音文件名是:bensound-november.mp3
我想无限播放这个文件。
我用的是打击码。
请建议适合此代码的简单代码。
import UIKit
import AVFoundation
class ViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
}
不确定它是否必须为 .wav 格式,但我有一些代码,请稍等。
//编辑
import UIKit
import AVFoundation
class ViewController: UIViewController {
var AudioPlayer = AVAudioPlayer()
override func viewDidLoad() {
super.viewDidLoad()
let AssortedMusics = NSURL(fileURLWithPath: NSBundle.mainBundle().pathForResource("bensound-november", ofType: "mp3")!)
AudioPlayer = try! AVAudioPlayer(contentsOfURL: AssortedMusics)
AudioPlayer.prepareToPlay()
AudioPlayer.numberOfLoops = -1
AudioPlayer.play()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
}
这应该有效,而且它也应该循环,因为如果使循环数 = -1,这就是它的效果,出于某种我不明白的原因,所以我不会解释它。
希望对您有所帮助!
只是提供 Bucket 答案的更新版本。谢谢
import AVFoundation
override func viewDidLoad() {
super.viewDidLoad()
let AssortedMusics = NSURL(fileURLWithPath: Bundle.main.path(forResource: "audioBg", ofType: "mp3")!)
AudioPlayer = try! AVAudioPlayer(contentsOf: AssortedMusics as URL)
AudioPlayer.prepareToPlay()
AudioPlayer.numberOfLoops = -1
AudioPlayer.play()
}
我的声音文件名是:bensound-november.mp3 我想无限播放这个文件。
我用的是打击码。 请建议适合此代码的简单代码。
import UIKit
import AVFoundation
class ViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
}
不确定它是否必须为 .wav 格式,但我有一些代码,请稍等。
//编辑
import UIKit
import AVFoundation
class ViewController: UIViewController {
var AudioPlayer = AVAudioPlayer()
override func viewDidLoad() {
super.viewDidLoad()
let AssortedMusics = NSURL(fileURLWithPath: NSBundle.mainBundle().pathForResource("bensound-november", ofType: "mp3")!)
AudioPlayer = try! AVAudioPlayer(contentsOfURL: AssortedMusics)
AudioPlayer.prepareToPlay()
AudioPlayer.numberOfLoops = -1
AudioPlayer.play()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
}
这应该有效,而且它也应该循环,因为如果使循环数 = -1,这就是它的效果,出于某种我不明白的原因,所以我不会解释它。
希望对您有所帮助!
只是提供 Bucket 答案的更新版本。谢谢
import AVFoundation
override func viewDidLoad() {
super.viewDidLoad()
let AssortedMusics = NSURL(fileURLWithPath: Bundle.main.path(forResource: "audioBg", ofType: "mp3")!)
AudioPlayer = try! AVAudioPlayer(contentsOf: AssortedMusics as URL)
AudioPlayer.prepareToPlay()
AudioPlayer.numberOfLoops = -1
AudioPlayer.play()
}