首页 文章

快速创作和播放声音

提问于
浏览
99

所以我想要做的就是在按下按钮时快速创建和播放声音,我知道如何在 Objective-C 中进行,但有没有人知道如何在 Swift 中?

对于 Objective-C 会是这样的:

NSURL *soundURL = [NSURL fileURLWithPath:[[NSBundle mainBundle] pathForResource:@"mysoundname" ofType:@"wav"]];
AudioServicesCreateSystemSoundID((__bridge CFURLRef)soundURL, &mySound);

然后玩它我会做:

AudioServicesPlaySystemSound(Explosion);

有谁知道我怎么做到这一点?

23 回答

  • 82

    以下是我添加到 FlappySwift 中的一些代码:

    import SpriteKit
    import AVFoundation
    
    class GameScene: SKScene {
    
        // Grab the path, make sure to add it to your project!
        var coinSound = NSURL(fileURLWithPath: Bundle.main.path(forResource: "coin", ofType: "wav")!)
        var audioPlayer = AVAudioPlayer()
    
        // Initial setup
        override func didMoveToView(view: SKView) {
            audioPlayer = AVAudioPlayer(contentsOfURL: coinSound, error: nil)
            audioPlayer.prepareToPlay()
        }
    
        // Trigger the sound effect when the player grabs the coin
        func didBeginContact(contact: SKPhysicsContact!) {
            audioPlayer.play()
        }
    
    }
    
  • 110

    这与其他一些答案类似,但也许更多“Swifty”:

    // Load "mysoundname.wav"
    if let soundURL = Bundle.main.url(forResource: "mysoundname", withExtension: "wav") {
        var mySound: SystemSoundID = 0
        AudioServicesCreateSystemSoundID(soundURL as CFURL, &mySound)
        // Play
        AudioServicesPlaySystemSound(mySound);
    }
    

    请注意,这是重现问题中代码效果的一个简单示例。您需要确保import AudioToolbox,加上这种代码的一般模式是在应用启动时加载声音,将它们保存在某处的SystemSoundID实例变量中,在整个应用中使用它们,然后在您启动时调用AudioServicesDisposeSystemSoundID他们完成了他们。

  • 17

    Handy Swift 扩展:

    import AudioToolbox
    
    extension SystemSoundID {
        static func playFileNamed(fileName: String, withExtenstion fileExtension: String) {
            var sound: SystemSoundID = 0
            if let soundURL = NSBundle.mainBundle().URLForResource(fileName, withExtension: fileExtension) {
                AudioServicesCreateSystemSoundID(soundURL, &sound)
                AudioServicesPlaySystemSound(sound)
            }
        }
    }
    

    然后,从你的应用程序的任何地方(记得import AudioToolbox),你可以打电话

    SystemSoundID.playFileNamed("sound", withExtenstion: "mp3")
    

    玩“sound.mp3”

  • 14

    这会从名为Cha-Ching.aiff的文件中创建SystemSoundID

    import AudioToolbox
    
    let chaChingSound: SystemSoundID = createChaChingSound()
    
    class CashRegisterViewController: UIViewController {
        override func viewWillAppear(animated: Bool) {
            super.viewWillAppear(animated)
            AudioServicesPlaySystemSound(chaChingSound)
        }
    }
    
    func createChaChingSound() -> SystemSoundID {
        var soundID: SystemSoundID = 0
        let soundURL = CFBundleCopyResourceURL(CFBundleGetMainBundle(), "Cha-Ching", "aiff", nil)
        AudioServicesCreateSystemSoundID(soundURL, &soundID)
        CFRelease(soundURL)
        return soundID
    }
    
  • 8

    使用 class&AudioToolbox:

    import AudioToolbox
    
    class Sound {
    
        var soundEffect: SystemSoundID = 0
        init(name: String, type: String) {
            let path  = NSBundle.mainBundle().pathForResource(name, ofType: type)!
            let pathURL = NSURL(fileURLWithPath: path)
            AudioServicesCreateSystemSoundID(pathURL as CFURLRef, &soundEffect)
        }
    
        func play() {
            AudioServicesPlaySystemSound(soundEffect)
        }
    }
    

    用法:

    testSound = Sound(name: "test", type: "caf")
    testSound.play()
    
  • 5
    import AVFoundation
    
    var audioPlayer = AVAudioPlayer()
    
    class GameScene: SKScene {
    
        override func didMoveToView(view: SKView) {
    
            let soundURL = NSBundle.mainBundle().URLForResource("04", withExtension: "mp3")
            audioPlayer = AVAudioPlayer(contentsOfURL: soundURL, error: nil)
            audioPlayer.play()
        }
    }
    
  • 5

    这段代码适合我。使用 Try 和 Catch for AVAudioPlayer

    import UIKit
    import AVFoundation
    class ViewController: UIViewController {
    
        //Make sure that sound file is present in your Project.
        var CatSound = NSURL(fileURLWithPath: NSBundle.mainBundle().pathForResource("Meow-sounds.mp3", ofType: "mp3")!)
        var audioPlayer = AVAudioPlayer()
    
        override func viewDidLoad() {
            super.viewDidLoad()
    
            do {
    
                audioPlayer = try AVAudioPlayer(contentsOfURL: CatSound)
                audioPlayer.prepareToPlay()
    
            } catch {
    
                print("Problem in getting File")
    
            }      
            // Do any additional setup after loading the view, typically from a nib.
        }
    
        override func didReceiveMemoryWarning() {
            super.didReceiveMemoryWarning()
            // Dispose of any resources that can be recreated.
        }
    
        @IBAction func button1Action(sender: AnyObject) {
    
            audioPlayer.play()
        }
    }
    
  • 4
    var mySound = NSSound(named:"Morse.aiff")
    mySound.play()
    

    “Morse.aiff”是 OSX 的系统声音,但如果您只是在 XCode 中单击“命名”,您将能够查看(在“快速帮助”窗格中)此功能搜索声音的位置。它可以位于“支持文件”文件夹中

  • 4

    根据新的 Swift 2.0 我们应该使用 try try catch。代码如下所示:

    var badumSound = NSURL(fileURLWithPath: NSBundle.mainBundle().pathForResource("BadumTss", ofType: "mp3"))
    var audioPlayer = AVAudioPlayer()
     do {
         player = try AVAudioPlayer(contentsOfURL: badumSound)
     } catch {
         print("No sound found by URL:\(badumSound)")
     }
     player.prepareToPlay()
    
  • 3

    这与 Swift 4 一起使用:

    if let soundURL = Bundle.main.url(forResource: "note3", withExtension: "wav") {
                    var mySound: SystemSoundID = 0
                    AudioServicesCreateSystemSoundID(soundURL as CFURL, &mySound)
                    // Play
                    AudioServicesPlaySystemSound(mySound);
                }
    
  • 3

    让我们看看这个问题的更新方法:

    Import AudioToolbox
    
    func noteSelector(noteNumber: String) {
    
        if let soundURL = Bundle.main.url(forResource: noteNumber, withExtension: "wav") {
            var mySound: SystemSoundID = 0
            AudioServicesCreateSystemSoundID(soundURL as CFURL, &mySound)
            AudioServicesPlaySystemSound(mySound)
    }
    
  • 2
    //Swift 4
    import UIKit
    import AVFoundation
    
    class ViewController: UIViewController {
    
        var player : AVAudioPlayer?
    
        override func viewDidLoad() {
            super.viewDidLoad()
        }
    
        @IBAction func notePressed(_ sender: UIButton) {
            let path = Bundle.main.path(forResource: "note1", ofType: "wav")!
            let url = URL(fileURLWithPath: path)
            do {
                player = try AVAudioPlayer(contentsOf: url)
                player?.play()
            } catch {
                // error message
            }
        }
    }
    
  • 1

    Matt Gibson 的解决方案对我有用,这里是 swift 3 版本。

    if let soundURL = Bundle.main.url(forResource: "ringSound", withExtension: "aiff") {
      var mySound: SystemSoundID = 0
      AudioServicesCreateSystemSoundID(soundURL as CFURL, &mySound)
      AudioServicesPlaySystemSound(mySound);
    }
    
  • 1

    斯威夫特 4

    import UIKit
    import AudioToolbox
    
    class ViewController: UIViewController{
    
    var sounds : [SystemSoundID] = [1, 2, 3, 4, 5, 6, 7]
    
    override func viewDidLoad() {
        super.viewDidLoad()
    
        for index in 0...sounds.count-1 {
            let fileName : String = "note\(sounds[index])"
    
            if let soundURL = Bundle.main.url(forResource: fileName, withExtension: "wav") {
                AudioServicesCreateSystemSoundID(soundURL as CFURL, &sounds[index])
            }
        }
    }
    
    @IBAction func notePressed(_ sender: UIButton) {
        switch sender.tag {
        case 1:
            AudioServicesPlaySystemSound(sounds[0])
        case 2:
            AudioServicesPlaySystemSound(sounds[1])
        case 3:
            AudioServicesPlaySystemSound(sounds[2])
        case 4:
            AudioServicesPlaySystemSound(sounds[3])
        case 5:
            AudioServicesPlaySystemSound(sounds[4])
        case 6:
            AudioServicesPlaySystemSound(sounds[5])
        default:
            AudioServicesPlaySystemSound(sounds[6])
        }
    }
    }
    

    要么

    import UIKit
    import AVFoundation
    
    class ViewController: UIViewController, AVAudioPlayerDelegate{
    
    var audioPlayer : AVAudioPlayer!
    
    override func viewDidLoad() {
        super.viewDidLoad()
    }
    
    @IBAction func notePressed(_ sender: UIButton) {
    
        let soundURL = Bundle.main.url(forResource: "note\(sender.tag)", withExtension: "wav")
    
        do {
            audioPlayer = try AVAudioPlayer(contentsOf: soundURL!)
        }
        catch {
            print(error)
        }
    
        audioPlayer.play()
    
    }
    }
    
  • 1

    Xcode 9.2工作

    if let soundURL = Bundle.main.url(forResource: "note1", withExtension: "wav") {
       var mySound: SystemSoundID = 0
       AudioServicesCreateSystemSoundID(soundURL as CFURL, &mySound)
       // Play
        AudioServicesPlaySystemSound(mySound);
     }
    
  • 1

    Swift 代码示例

    import UIKit
    import AudioToolbox
    
    class ViewController: UIViewController {  
    
    override func viewDidLoad() {
        super.viewDidLoad()
    }
    
    @IBAction func notePressed(_ sender: UIButton) {
    
        // Load "mysoundname.wav"
    
        if let soundURL = Bundle.main.url(forResource: "note1", withExtension: "wav") {
            var mySound: SystemSoundID = 0
            AudioServicesCreateSystemSoundID(soundURL as CFURL, &mySound)
        // Play
    
            AudioServicesPlaySystemSound(mySound);
        }
    }
    
  • 1

    你可以在 Swift 5.2 中试试这个:

    func playSound() {
            let soundURL = Bundle.main.url(forResource: selectedSoundFileName, withExtension: "wav")
            do {
                audioPlayer = try AVAudioPlayer(contentsOf: soundURL!)
            }
            catch {
                print(error)
            }
            audioPlayer.play()
        }
    
  • 1

    swift 4 和 iOS 12

    var audioPlayer: AVAudioPlayer?
    
    override func viewDidLoad() {
        super.viewDidLoad()
    
    }
    
    @IBAction func notePressed(_ sender: UIButton) {
    
        // noise while pressing button
    
        _ = Bundle.main.path(forResource: "note1", ofType: "wav")
    
        if Bundle.main.path(forResource: "note1", ofType: "wav") != nil {
            print("Continue processing")
        } else {
            print("Error: No file with specified name exists")
        }
    
        do {
            if let fileURL = Bundle.main.path(forResource: "note1", ofType: "wav") {
                audioPlayer = try AVAudioPlayer(contentsOf: URL(fileURLWithPath: fileURL))
            } else {
                print("No file with specified name exists")
            }
        } catch let error {
            print("Can't play the audio file failed with an error \(error.localizedDescription)")
        }
    
        audioPlayer?.play()    }
    

    }

  • 0

    使用此功能在 Swift 中发出声音(您可以在此处使用此功能 sound.)

    首先添加 SpriteKit 和 AVFoundation Framework。

    import SpriteKit
    import AVFoundation
     func playEffectSound(filename: String){
       runAction(SKAction.playSoundFileNamed("\(filename)", waitForCompletion: false))
     }// use this function to play sound
    
    playEffectSound("Sound File Name With Extension")
    // Example :- playEffectSound("BS_SpiderWeb_CollectEgg_SFX.mp3")
    
  • 0

    这段代码适合我:

    class ViewController: UIViewController {
    
        var audioFilePathURL : NSURL!
        var soundSystemServicesId : SystemSoundID = 0
    
        override func viewDidLoad() {
            super.viewDidLoad()
            // Do any additional setup after loading the view, typically from a nib.
            audioFilePathURL = NSBundle.mainBundle().URLForResource("MetalBell", withExtension: "wav")
    
            AudioServicesCreateSystemSoundID( audioFilePathURL, &soundSystemServicesId)
    
        }
    
        override func didReceiveMemoryWarning() {
            super.didReceiveMemoryWarning()
            // Dispose of any resources that can be recreated.
    
        }
    
        @IBAction func PlayAlertSound(sender: UIButton) {
    
             AudioServicesPlayAlertSound(soundSystemServicesId)
        }
    }
    
  • 0

    对于Swift 3

    extension SystemSoundID {
        static func playFileNamed(_ fileName: String, withExtenstion fileExtension: String) {
            var sound: SystemSoundID = 0
            if let soundURL = Bundle.main.url(forResource: fileName, withExtension: fileExtension) {
                AudioServicesCreateSystemSoundID(soundURL as CFURL, &sound)
                AudioServicesPlaySystemSound(sound)
            }
        }
    }
    
  • 0

    Swift 3 就是我这样做的。

    {
    
    import UIKit
    import AVFoundation
    
            let url = Bundle.main.url(forResource: "yoursoundname", withExtension: "wav")!
            do {
    
                player = try AVAudioPlayer(contentsOf: url); guard let player = player else { return }
    
                player.prepareToPlay()
                player.play()
            } catch let error as Error {
                print(error)
    
            }
        }
    
  • 0

    难道你不能只是import AVFoundation,选择音频播放器(var audioPlayer : AVAudioPlayer!),然后播放声音? (let soundURL = Bundle.main.url(forResource: "sound", withExtension: "wav")

相关问题