小编典典

如何使用 Swift 播放声音?

all

我想使用 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
  }
}

阅读 221

收藏
2022-06-13

共1个答案

小编典典

最好你可能想使用 AVFoundation。它提供了使用视听媒体的所有必需品。

更新:与 Swift 2Swift 3Swift 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)。您可能希望将其放入assets.xcassets以提供更大的便利。

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


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

2022-06-13