首页 文章

如何使用 Swift 播放声音?

提问于
浏览
95

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

13 回答

  • 1

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

    最好您可能想要使用 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 12 兼容)

    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中以方便使用。

    对于简短的声音文件,您可能希望使用 non-compressed 音频格式,例如.wav,因为它们具有最佳质量和较低的 CPU 影响。对于短声音文件,较高的 disk-space 消耗不应该是一个大问题。文件越长,您可能想要使用压缩格式,例如.mp3等。检查CoreAudio兼容的音频格式


    **Fun-fact:**有一些简洁的小库,使播放声音更容易。 :)
    例如:SwiftySound

  • 37

    对于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)")
        }
    }
    

    本地资产的最佳做法是将其放在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)")
        }
    }
    
  • 14

    iOS 12 - Xcode 10 beta 6 - Swift 4.2

    仅使用 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!")
    
            }
    
    }
    
  • 8

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

    static var player: AVAudioPlayer!
    

    对我来说,当我做这个改变时,第一个解决方案起作用:)

  • 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
    }
    
  • 1

    首先导入这些库

    import AVFoundation
    
    import AudioToolbox
    

    像这样设置委托

    AVAudioPlayerDelegate
    

    在按钮动作或某些动作上写下漂亮的代码:

    guard let url = Bundle.main.url(forResource: "ring", withExtension: "mp3") else { return }
        do {
            try AVAudioSession.sharedInstance().setCategory(AVAudioSessionCategoryPlayback)
            try AVAudioSession.sharedInstance().setActive(true)
            player = try AVAudioPlayer(contentsOf: url, fileTypeHint: AVFileType.mp3.rawValue)
            guard let player = player else { return }
    
            player.play()
        }catch let error{
            print(error.localizedDescription)
        }
    

    100%在我的项目中工作并经过测试

  • 1

    使用 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)
        }
    }
    
  • 1

    非常简单的代码快速

    将您的音频文件添加到您的 Xcode 并给出给定的代码

    import AVFoundation
    
    class ViewController: UIViewController{
    
       var audioPlayer = AVAudioPlayer() //declare as Globally
    
       override func viewDidLoad() {
            super.viewDidLoad()
    
            guard let sound = Bundle.main.path(forResource: "audiofilename", ofType: "mp3") else {
                print("error to get the mp3 file")
                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()
    }
    
  • 0
    func playSound(_ buttonTag : Int){
    
        let path = Bundle.main.path(forResource: "note\(buttonTag)", ofType : "wav")!
        let url = URL(fileURLWithPath : path)
    
        do{
            soundEffect = try AVAudioPlayer(contentsOf: url)
            soundEffect?.play()
            // to stop the spound .stop()
        }catch{
            print ("file could not be loaded or other error!")
        }
    }
    

    适用于 swift 4 最新版本。 ButtonTag 将是您界面上按钮的标签。 Notes 位于与 Main.storyboard 平行的文件夹中的文件夹中。每个音符都被命名为 note1,note2 等.ButtonTag 从点击的按钮给出数字 1,2 等,作为参数传递

  • 0
    import UIKit
    import AVFoundation
    
    class ViewController: UIViewController{
    
        var player: AVAudioPlayer?
    
        override func viewDidLoad() {
            super.viewDidLoad()
        }
    
        @IBAction func notePressed(_ sender: UIButton) {
    
            guard let url = Bundle.main.url(forResource: "note1", withExtension: "wav") else { return }
    
            do {
                try AVAudioSession.sharedInstance().setCategory((AVAudioSession.Category.playback), mode: .default, options: [])
                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.wav.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)
            }
    
        }
    
    }
    
  • 0

    Swift 4,4.2 和 5

    播放来自 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()
        }
    
    }
    
  • -1
    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()
        }
    

相关问题