ios 如何使用 Swift 播放声音?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/32036146/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-31 07:17:49  来源:igfitidea点击:

How to play a sound using Swift?

iosswiftavfoundation

提问by Michel Kansou

I would like to play a sound using Swift.

我想使用 Swift 播放声音。

My code worked in Swift 1.0 but now it doesn't work anymore in Swift 2 or newer.

我的代码在 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
  }
}

回答by Devapploper

Most preferably you might want to use AVFoundation. It provides all the essentials for working with audiovisual media.

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

Update:Compatible with Swift 2, Swift 3and Swift 4as suggested by some of you in the comments.

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



Swift 2.3

斯威夫特 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)
    }
}


Swift 3

斯威夫特 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 compatible)

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)
    }
}

Make sure to change the name of your tune as well as the extension.The file needs to be properly imported (Project Build Phases> Copy Bundle Resources). You might want to place it in assets.xcassetsfor greater convenience.

确保更改您的曲调名称以及扩展名该文件需要正确导入 ( Project Build Phases> Copy Bundle Resources)。assets.xcassets为了更方便,您可能希望将其放入。

For short sound files you might want to go for non-compressed audio formats such as .wavsince they have the best quality and a low cpu impact. The higher disk-space consumption should not be a big deal for short sound files. The longer the files are, you might want to go for a compressed format such as .mp3etc. pp. Check the compatible audio formatsof CoreAudio.

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



Fun-fact:There are neat little libraries which make playing sounds even easier. :)
For example: SwiftySound

有趣的事实:有一些整洁的小库,使播放声音变得更加容易。:)
例如:SwiftySound

回答by Adi Nugroho

For Swift 3:

对于Swift 3

import AVFoundation

/// **must** define instance variable outside, because .play() will deallocate AVAudioPlayer 
/// immediately and you won't hear a thing
var player: AVAudioPlayer?

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

    do {
        /// this codes for making this app ready to takeover the device audio
        try AVAudioSession.sharedInstance().setCategory(AVAudioSessionCategoryPlayback)
        try AVAudioSession.sharedInstance().setActive(true)

        /// change fileTypeHint according to the type of your audio file (you can omit this)

        player = try AVAudioPlayer(contentsOf: url, fileTypeHint: AVFileTypeMPEGLayer3)

        // no need for prepareToPlay because prepareToPlay is happen automatically when calling play()
        player!.play()
    } catch let error as NSError {
        print("error: \(error.localizedDescription)")
    }
}

The best practice for local assets is to put it inside assets.xcassetsand you load the file like this :

本地资产的最佳做法是将其放入其中,assets.xcassets然后像这样加载文件:

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

    do {
        /// this codes for making this app ready to takeover the device audio
        try AVAudioSession.sharedInstance().setCategory(AVAudioSessionCategoryPlayback)
        try AVAudioSession.sharedInstance().setActive(true)

        /// change fileTypeHint according to the type of your audio file (you can omit this)

        /// for iOS 11 onward, use :
        player = try AVAudioPlayer(contentsOf: url, fileTypeHint: AVFileType.mp3.rawValue)

        /// else :
        /// player = try AVAudioPlayer(contentsOf: url, fileTypeHint: AVFileTypeMPEGLayer3)

        // no need for prepareToPlay because prepareToPlay is happen automatically when calling play()
        player!.play()
    } catch let error as NSError {
        print("error: \(error.localizedDescription)")
    }
}

回答by Tony Ward

iOS 12 - Xcode 10 beta 6 - Swift 4.2

iOS 12 - Xcode 10 测试版 6 - Swift 4.2

Use just 1 IBAction and point all the buttons to that 1 action.

仅使用 1 个 IBAction 并将所有按钮指向该 1 个操作。

import AVFoundation

var player = AVAudioPlayer()

@IBAction func notePressed(_ sender: UIButton) {
    print(sender.tag) // testing button pressed tag
    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 {
        print ("There is an issue with this code!")
    }
}

回答by EranKT

If code doesn't generate any error, but you don't hear sound - create the player as an instance:

如果代码没有产生任何错误,但您没有听到声音 - 将播放器创建为一个实例:

   static var player: AVAudioPlayer!

For me the first solution worked when I did this change :)

对我来说,当我进行此更改时,第一个解决方案起作用了:)

回答by Mr.Shin

Swift 3

斯威夫特 3

import AVFoundation


var myAudio: AVAudioPlayer!

    let path = Bundle.main.path(forResource: "example", ofType: "mp3")!
    let url = URL(fileURLWithPath: path)
do {
    let sound = try AVAudioPlayer(contentsOf: url)
    myAudio = sound
    sound.play()
} catch {
    // 
}

//If you want to stop the sound, you should use its stop()method.if you try to stop a sound that doesn't exist your app will crash, so it's best to check that it exists.

if myAudio != nil {
    myAudio.stop()
    myAudio = nil
}

回答by Akbar Khan

Swift 4, 4.2 and 5

斯威夫特 4、4.2 和 5

Play audio from URL and from your project (Local File)

从 URL 和您的项目(本地文件)播放音频

import UIKit
import AVFoundation

class ViewController: UIViewController{

var audioPlayer : AVPlayer!

override func viewDidLoad() {
        super.viewDidLoad()
// call what ever function you want.
    }

    private func playAudioFromURL() {
        guard let url = URL(string: "https://geekanddummy.com/wp-content/uploads/2014/01/coin-spin-light.mp3") else {
            print("error to get the mp3 file")
            return
        }
        do {
            audioPlayer = try AVPlayer(url: url as URL)
        } catch {
            print("audio file error")
        }
        audioPlayer?.play()
    }

    private func playAudioFromProject() {
        guard let url = Bundle.main.url(forResource: "azanMakkah2016", withExtension: "mp3") else {
            print("error to get the mp3 file")
            return
        }

        do {
            audioPlayer = try AVPlayer(url: url)
        } catch {
            print("audio file error")
        }
        audioPlayer?.play()
    }

}

回答by Fattie

Game style:

游戏风格:

file Sfx.swift

文件 Sfx.swift

import AVFoundation

public let sfx = Sfx.shared
public final class Sfx: NSObject {

    static let shared = Sfx()

    var apCheer: AVAudioPlayer? = nil

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

    func cheer() { apCheer?.play() }
    func plonk() { apPlonk?.play() }
    func crack() { apCrack?.play() } .. etc
}

Anywhere at all in code

代码中的任何地方

sfx.explosion()
sfx.cheer()

回答by Ershin Bot

Tested with Swift 4 and iOS 12:

使用 Swift 4 和 iOS 12 测试:

import UIKit
import AVFoundation
class ViewController: UIViewController{
    var player: AVAudioPlayer!
    override func viewDidLoad() {
        super.viewDidLoad()
    }

    func playTone(number: Int) {
        let path = Bundle.main.path(forResource: "note\(number)", ofType : "wav")!
        let url = URL(fileURLWithPath : path)
        do {
            player = try AVAudioPlayer(contentsOf: url)
            print ("note\(number)")
            player.play()
        }
        catch {
            print (error)
        }
    }

    @IBAction func notePressed(_ sender: UIButton) {
        playTone(number: sender.tag)
    }
}

回答by M VIJAY

This is basic code to find and play an audio file in Swift.

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

Add your audio file to your Xcode and add the code below.

将您的音频文件添加到您的 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()
    }
}

回答by imdpk

Swift 4 (iOS 12 compatible)

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)
}