插入背景音乐的简便方法'在Swift Xcode中

时间:2015-12-28 04:32:32

标签: swift avfoundation audio-player

我的声音文件名是:bensound-november.mp3 我想播放一个无限的文件。

我使用吹码。 请建议使用此代码的简单代码。

import UIKit
import AVFoundation

class ViewController: UIViewController {






override func viewDidLoad() {
    super.viewDidLoad()

}

override func didReceiveMemoryWarning() {
    super.didReceiveMemoryWarning()
}
}

2 个答案:

答案 0 :(得分:1)

不确定它是否必须是.wav格式,但我有一些代码给我一秒钟。

// EDIT

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,那就是由于某种原因我不理解的效果,所以我不会解释它。

希望有所帮助!

答案 1 :(得分:0)

只提供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()
    }