如何用swift 2.0播放背景音乐?

时间:2015-10-01 08:21:29

标签: ios xcode swift swift2

我是swift和ios开发的新手。我的代码一直在运行,直到我更新到Swift 2.0,我使用了swift迁移工具,但我仍然无法弄清楚如何对代码进行排序和修复。请帮忙!

<xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema" version="1.0">
  <xs:simpleType name="addressType">
    <xs:restriction base="xs:string">
      <xs:enumeration value="CC"/>
      <xs:enumeration value="BCC"/>
      <xs:enumeration value="TO"/>
      <xs:enumeration value="REPLY_TO"/>
    </xs:restriction>
  </xs:simpleType>
</xs:schema>

2 个答案:

答案 0 :(得分:17)

更新了swift 2.0的功能:

import AVFoundation

var backgroundMusicPlayer = AVAudioPlayer()

func playBackgroundMusic(filename: String) {
    let url = NSBundle.mainBundle().URLForResource(filename, withExtension: nil)
    guard let newURL = url else {
        print("Could not find file: \(filename)")
        return
    }
    do {
        backgroundMusicPlayer = try AVAudioPlayer(contentsOfURL: newURL)
        backgroundMusicPlayer.numberOfLoops = -1
        backgroundMusicPlayer.prepareToPlay()
        backgroundMusicPlayer.play()
    } catch let error as NSError {
        print(error.description)
    }
}

以这种方式使用:

playBackgroundMusic("yourFileName.mp3")

答案 1 :(得分:1)

您也可以启用会话以进行后台播放功能。

func enableBackgroundPlaying(_ enable: Bool) throws {
    do {
        try AVAudioSession.sharedInstance().setCategory(AVAudioSessionCategoryPlayback)
        do {
            try AVAudioSession.sharedInstance().setActive(enable)
        } catch {
            throw error
        }
    } catch {
        throw error
    }
}