快速创作和播放声音

Jac*_*nks 99 audio objective-c ios swift

所以我想要做的是快速创建并播放声音,当我按下按钮时会播放,我知道如何在Objective-C中执行此操作,但有人知道如何在Swift中播放吗?

对于Objective-C,它会是这样的:

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

然后玩它我会做:

AudioServicesPlaySystemSound(Explosion);
Run Code Online (Sandbox Code Playgroud)

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

Mat*_*son 113

这与其他一些答案类似,但也许更多"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);
}
Run Code Online (Sandbox Code Playgroud)

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


小智 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()
    }

}
Run Code Online (Sandbox Code Playgroud)

  • 在Swift 2中记得以这样的方式运行它`do {(player object)} catch _ {}`或者你的bug会出错!:) (3认同)

小智 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)
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

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

SystemSoundID.playFileNamed("sound", withExtenstion: "mp3")
Run Code Online (Sandbox Code Playgroud)

玩"sound.mp3"


ma1*_*w28 14

SystemSoundID将从一个名为的文件创建一个Cha-Ching.aiff.

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
}
Run Code Online (Sandbox Code Playgroud)

  • 鉴于提供的Obj-C示例基于AudioToolBox框架,这应该是公认的答案 (2认同)

kar*_*bux 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)
    }
}
Run Code Online (Sandbox Code Playgroud)

用法:

testSound = Sound(name: "test", type: "caf")
testSound.play()
Run Code Online (Sandbox Code Playgroud)

  • 我喜欢这个答案.另外因为它是系统声音,我没有得到AVAudioPlayer在xcode 8的控制台中抛出的系统消息. (2认同)

Mic*_*l N 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()
    }
}
Run Code Online (Sandbox Code Playgroud)


Sac*_*iya 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()
    }
}
Run Code Online (Sandbox Code Playgroud)