我想用Swift播放一个声音。

我的代码在Swift 1.0中工作,但现在在Swift 2或更新版本中不再工作。

override func viewDidLoad() {
  super.viewDidLoad()

  let url:NSURL = NSBundle.mainBundle().URLForResource("soundName", withExtension: "mp3")!

  do { 
    player = try AVAudioPlayer(contentsOfURL: url, fileTypeHint: nil) 
  } catch _{
    return
  }

  bgMusic.numberOfLoops = 1
  bgMusic.prepareToPlay()

  if (Data.backgroundMenuPlayed == 0){
    player.play()
    Data.backgroundMenuPlayed = 1
  }
}

当前回答

Swift版本:5.4及以上

import AVFoundation
var player: AVAudioPlayer?

func playSound() {
    guard let path = Bundle.main.path(forResource: "beep", ofType:"mp3") else {
        return }
    let url = URL(fileURLWithPath: path)

    do {
        player = try AVAudioPlayer(contentsOf: url)
        player?.play()
        
    } catch let error {
        print(error.localizedDescription)
    }
}

其他回答

游戏风格:

文件Sfx.swift

import AVFoundation

public let sfx = Sfx.shared
public final class Sfx: NSObject {
    
    static let shared = Sfx()
    
    var apCheer: AVAudioPlayer? = nil
    // etc
    
    private override init() {
        guard let s = Bundle.main.path(forResource: "cheer", ofType: "mp3") else { print("Sfx woe"); return }
        do { apCheer = try AVAudioPlayer(contentsOf: URL(fileURLWithPath: s)) } catch { print("Sfx woe"); return }
        // etc
    }
    
    func cheer() { apCheer?.play() }
    func plonk() { apPlonk?.play() }
    func crack() { apCrack?.play() }
    // etc
}

只要吃一个……

    var apCheer: AVAudioPlayer? = nil

对于你的每一个音频刺。所以你可能有5 20 10等等。

对于每一个,简单地复制/粘贴两行初始化代码:

guard let s = Bundle.main.path(forResource: "cheer", ofType: "mp3") else { return print("Sfx woe") }
do { apCheer = try AVAudioPlayer(contentsOf: URL(fileURLWithPath: s)) } catch { return print("Sfx woe") }

然后,在任何地方,任何代码,任何文件,你都可以:

sfx.cheer()
sfx.crack()

最好使用AVFoundation。 它提供了所有与视听媒体工作的必要条件。

更新:兼容Swift 2, Swift 3和Swift 4,正如你们中的一些人在评论中建议的那样。


斯威夫特2.3

import AVFoundation

var player: AVAudioPlayer?

func playSound() {
    let url = NSBundle.mainBundle().URLForResource("soundName", withExtension: "mp3")!

    do {
        player = try AVAudioPlayer(contentsOfURL: url)
        guard let player = player else { return }

        player.prepareToPlay()
        player.play()

    } catch let error as NSError {
        print(error.description)
    }
}

斯威夫特3

import AVFoundation

var player: AVAudioPlayer?

func playSound() {
    guard let url = Bundle.main.url(forResource: "soundName", withExtension: "mp3") else { return }

    do {
        try AVAudioSession.sharedInstance().setCategory(AVAudioSessionCategoryPlayback)
        try AVAudioSession.sharedInstance().setActive(true)

        let player = try AVAudioPlayer(contentsOf: url)

        player.play()

    } catch let error {
        print(error.localizedDescription)
    }
}

Swift 4(兼容iOS 13)

import AVFoundation

var player: AVAudioPlayer?

func playSound() {
    guard let url = Bundle.main.url(forResource: "soundName", withExtension: "mp3") else { return }

    do {
        try AVAudioSession.sharedInstance().setCategory(.playback, mode: .default)            
        try AVAudioSession.sharedInstance().setActive(true)

        /* The following line is required for the player to work on iOS 11. Change the file type accordingly*/
        player = try AVAudioPlayer(contentsOf: url, fileTypeHint: AVFileType.mp3.rawValue)

        /* iOS 10 and earlier require the following line:
        player = try AVAudioPlayer(contentsOf: url, fileTypeHint: AVFileTypeMPEGLayer3) */

        guard let player = player else { return }

        player.play()

    } catch let error {
        print(error.localizedDescription)
    }
}

请确保更改您的曲调的名称以及扩展名。 文件需要正确导入(Project Build Phases > Copy Bundle Resources)。你可以把它放在资产里。xcassets为 更大的便利。

对于短音频文件,你可能想要使用非压缩音频格式,如。wav,因为它们具有最好的质量和低cpu消耗。对于较短的声音文件来说,较高的磁盘空间消耗应该不是什么大问题。文件越长,你可能想要使用压缩格式,如。mp3等。检查CoreAudio的兼容音频格式。


有趣的事实:有一些整洁的小库可以让播放声音更容易。:) 例如:SwiftySound

import AVFoundation
var player:AVAudioPlayer!

func Play(){
    guard let path = Bundle.main.path(forResource: "KurdishSong", ofType: "mp3")else{return}
    let soundURl = URL(fileURLWithPath: path)
    player = try? AVAudioPlayer(contentsOf: soundURl)
    player.prepareToPlay()
    player.play()
    //player.pause()
    //player.stop()
}

这是在Swift中查找和播放音频文件的基本代码。

将音频文件添加到Xcode中,并添加下面的代码。

import AVFoundation

class ViewController: UIViewController {

   var audioPlayer = AVAudioPlayer() // declare globally

   override func viewDidLoad() {
        super.viewDidLoad()

        guard let sound = Bundle.main.path(forResource: "audiofilename", ofType: "mp3") else {
            print("Error getting the mp3 file from the main bundle.")
            return
        }
        do {
            audioPlayer = try AVAudioPlayer(contentsOf: URL(fileURLWithPath: sound))
        } catch {
            print("Audio file error.")
        }
        audioPlayer.play()
    }

    @IBAction func notePressed(_ sender: UIButton) { // Button action
        audioPlayer.stop()
    }
}

Swift 4(兼容iOS 12)

var player: AVAudioPlayer?

let path = Bundle.main.path(forResource: "note\(sender.tag)", ofType: "wav")
let url = URL(fileURLWithPath: path ?? "")
    
do {
   player = try AVAudioPlayer(contentsOf: url)
   player?.play()
} catch let error {
   print(error.localizedDescription)
}