ios 快速创建和播放声音
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/24043904/
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
Creating and playing a sound in swift
提问by Jacob Banks
So what I want to do is create and play a sound in swift that will play when I press a button, I know how to do it in Objective-C, but does anyone know how to in Swift?
所以我想要做的是在 swift 中创建和播放一个声音,当我按下按钮时会播放,我知道如何在 Objective-C 中做到这一点,但有没有人知道如何在 Swift 中做到这一点?
It would be like this for Objective-C:
对于Objective-C 来说是这样的:
NSURL *soundURL = [NSURL fileURLWithPath:[[NSBundle mainBundle] pathForResource:@"mysoundname" ofType:@"wav"]];
AudioServicesCreateSystemSoundID((__bridge CFURLRef)soundURL, &mySound);
And then to play it I would do:
然后玩它我会这样做:
AudioServicesPlaySystemSound(Explosion);
Does anyone know how I could do this?
有谁知道我怎么能做到这一点?
采纳答案by Bauerpauer
Here's a bit of code I've got added to FlappySwift that works:
这是我添加到 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()
}
}
回答by Matt Gibson
This is similar to some other answers, but perhaps a little more "Swifty":
这类似于其他一些答案,但可能更“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);
}
Note that this is a trivial example reproducing the effect of the code in the question. You'll need to make sure to import AudioToolbox
, plus the general pattern for this kind of code would be to load your sounds when your app starts up, saving them in SystemSoundID
instance variables somewhere, use them throughout your app, then call AudioServicesDisposeSystemSoundID
when you're finished with them.
请注意,这是一个简单的示例,可重现问题中代码的效果。你需要确保import AudioToolbox
,加上这种代码的一般模式是在你的应用程序启动时加载你的声音,将它们保存在SystemSoundID
某个地方的实例变量中,在你的应用程序中使用它们,然后AudioServicesDisposeSystemSoundID
在你完成后调用跟他们。
回答by Aleix Pinardell
Handy Swift extension:
方便的 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)
}
}
}
Then, from anywhere in your app (remember to import AudioToolbox
), you can call
然后,从您应用程序的任何位置(请记住import AudioToolbox
),您可以调用
SystemSoundID.playFileNamed("sound", withExtenstion: "mp3")
to play "sound.mp3"
播放“sound.mp3”
回答by ma11hew28
This creates a SystemSoundID
from a file called Cha-Ching.aiff
.
这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
}
回答by karimhossenbux
With a class & AudioToolbox:
使用类和 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)
}
}
Usage:
用法:
testSound = Sound(name: "test", type: "caf")
testSound.play()
回答by Sachin Dobariya
This code works for me. Use Try and Catch for AVAudioPlayer
这段代码对我有用。对 AVAudioPlayer 使用 Try and Catch
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()
}
}
回答by Michael N
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()
}
}
回答by Roman Safin
According to new Swift 2.0 we should use do try catch. The code would look like this:
根据新的 Swift 2.0,我们应该使用 do 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()
回答by philippe
var mySound = NSSound(named:"Morse.aiff")
mySound.play()
"Morse.aiff" is a system sound of OSX, but if you just click on "named" within XCode, you'll be able to view (in the QuickHelp pane) where this function is searching the sounds. It can be in your "Supporting files" folder
“Morse.aiff”是 OSX 的系统声音,但如果您只在 XCode 中单击“named”,您将能够(在 QuickHelp 窗格中)查看此功能搜索声音的位置。它可以在您的“支持文件”文件夹中
回答by Mohammad Aboelnasr
this is working with Swift 4 :
这是与 Swift 4 一起使用的:
if let soundURL = Bundle.main.url(forResource: "note3", withExtension: "wav") {
var mySound: SystemSoundID = 0
AudioServicesCreateSystemSoundID(soundURL as CFURL, &mySound)
// Play
AudioServicesPlaySystemSound(mySound);
}