빠른 소리 생성 및 재생
그래서 제가 하고 싶은 일은 버튼을 누르면 재생되는 소리를 빠르게 만들고 재생하는 것입니다. 저는 Objective-C에서 어떻게 하는지 알고 있지만 스위프트에서 어떻게 하는지 아는 사람이 있습니까?
목표-C의 경우 이와 같습니다.
NSURL *soundURL = [NSURL fileURLWithPath:[[NSBundle mainBundle] pathForResource:@"mysoundname" ofType:@"wav"]];
AudioServicesCreateSystemSoundID((__bridge CFURLRef)soundURL, &mySound);
그리고 나서 연주를 하기 위해 나는 다음과 같이 했습니다.
AudioServicesPlaySystemSound(Explosion);
내가 이걸 어떻게 할 수 있는지 아는 사람?
이는 일부 다른 답변과 비슷하지만, 아마도 조금 더 "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
당신이 그들과 끝이 나면요.
FlapySwift에 추가한 코드는 다음과 같습니다.
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()
}
}
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"을 재생하다
이렇게 하면 다음이 생성됩니다.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
}
클래스 & 오디오 도구 상자 사용:
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()
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()
}
}
이 코드는 제게 적합합니다.AV 오디오 플레이어에 시도 및 잡기 사용
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()
}
}
var mySound = NSSound(named:"Morse.aiff")
mySound.play()
"Morse.aiff"는 OSX의 시스템 사운드이지만 XCode 내의 "이름 지정"을 클릭하기만 하면 이 기능이 사운드를 검색하는 곳을 (QuickHelp 창에서) 볼 수 있습니다.지원하는 파일 폴더에 있을 수 있습니다.
새로운 스위프트 2.0에 따르면 우리는 dory 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()
Swift 4와 함께 작동합니다.
if let soundURL = Bundle.main.url(forResource: "note3", withExtension: "wav") {
var mySound: SystemSoundID = 0
AudioServicesCreateSystemSoundID(soundURL as CFURL, &mySound)
// Play
AudioServicesPlaySystemSound(mySound);
}
//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
}
}
}
이 질문에 대한 보다 업데이트된 접근 방식을 살펴보겠습니다.
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)
}
import UIKit
import AudioToolbox
class ViewController: UIViewController {
let toneSound : Array = ["note1","note2","note3","note4","note5","note6"]
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
}
func playSound(theTone : String) {
if let soundURL = Bundle.main.url(forResource: theTone, withExtension: "wav") {
var mySound: SystemSoundID = 0
do {
AudioServicesCreateSystemSoundID(soundURL as CFURL, &mySound)
// Play
AudioServicesPlaySystemSound(mySound);
}
catch {
print(error)
}
}
}
@IBAction func anypressed(_ sender: UIButton) {
playSound(theTone: toneSound[sender.tag-1] )
}
}
스위프트 5.2에서 사용해 볼 수 있습니다.
func playSound() {
let soundURL = Bundle.main.url(forResource: selectedSoundFileName, withExtension: "wav")
do {
audioPlayer = try AVAudioPlayer(contentsOf: soundURL!)
}
catch {
print(error)
}
audioPlayer.play()
}
스위프트 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)
}
}
}
매트 깁슨의 솔루션이 효과가 있었습니다, swift 3 버전입니다.
if let soundURL = Bundle.main.url(forResource: "ringSound", withExtension: "aiff") {
var mySound: SystemSoundID = 0
AudioServicesCreateSystemSoundID(soundURL as CFURL, &mySound)
AudioServicesPlaySystemSound(mySound);
}
스위프트 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()
}
}
일을 하는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);
}
스위프트 코드 예제:
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);
}
}
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() }
}
스위프트에서 소리를 내려면 이 기능을 사용하세요. (소리를 내고 싶은 곳에 이 기능을 사용하시면 됩니다.
우선 스프라이트 키트와 AV 파운데이션 프레임워크를 추가합니다.
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")
이 코드는 제게 적합합니다.
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)
}
}
스위프트 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)
}
}
당신은 그냥.import AVFoundation
, 오디오 플레이어를 선택합니다(var audioPlayer : AVAudioPlayer!
(), 소리를 재생합니까?)let soundURL = Bundle.main.url(forResource: "sound", withExtension: "wav"
)
언급URL : https://stackoverflow.com/questions/24043904/creating-and-playing-a-sound-in-swift
'it-source' 카테고리의 다른 글
jQuery에서 prop()와 attr()의 차이 및 attr()와 prop()의 사용 시기 (0) | 2023.09.18 |
---|---|
이 Google Play APK 게시 오류 메시지의 의미는 무엇입니까? (0) | 2023.09.18 |
C 프로그래머들이 C++를 쓰기 시작한 나쁜 습관은 무엇입니까? (0) | 2023.09.18 |
테마 및 플러그인 설치를 시도하는 바인딩 마운트 볼륨에 대한 도커/워드프레스/디코딩 권한 (0) | 2023.09.18 |
클래스 사용 시기 vs.PHP에서의 기능 (0) | 2023.09.18 |