创建和迅速播放声音 [英] Creating and playing a sound in swift

查看:98
本文介绍了创建和迅速播放声音的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

所以,我想要做的是创造和发挥迅速的声音时我preSS一个按钮,会玩,我知道如何做到这一点在Objective-C,但没有人知道如何在斯威夫特<? / p>

这会是这样的Objective-C的:

  NSURL * soundURL = [NSURL fileURLWithPath:[一个NSBundle mainBundle] pathForResource:@mysoundnameofType:@WAV]];
AudioServicesCreateSystemSoundID((__桥CFURLRef)soundURL,&安培;为mySound);

然后打它,我会做:

  AudioServicesPlaySystemSound(爆炸);

有谁知道我怎么能这样做呢?


解决方案

下面是一个有点code我得加FlappySwift的的作品:

 进口SpriteKit
进口AVFoundation类GameScene:SKScene {    //取得的路径,请确保将其添加到您的项目!
    VAR coinSound = NSURL(fileURLWithPath:NSBundle.mainBundle()pathForResource(硬币,ofType:WAV))
    VAR audioPlayer = AVAudioPlayer()    // 初始设置
    覆盖FUNC didMoveToView(查看:SKView){
        audioPlayer = AVAudioPlayer(contentsOfURL:coinSound,错误:无)
        audioPlayer。prepareToPlay()
    }    当玩家抓住硬币//触发音效
    FUNC didBeginContact(联系人:SKPhysicsContact!){
        audioPlayer.play()
    }}

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?

It would be like this for 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?

解决方案

Here's a bit of code I've got added to FlappySwift that works:

import SpriteKit
import AVFoundation

class GameScene: SKScene {

    // Grab the path, make sure to add it to your project!
    var coinSound = NSURL(fileURLWithPath: NSBundle.mainBundle().pathForResource("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()
    }

}

这篇关于创建和迅速播放声音的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆