【问题标题】:Inserting sound on Xcode 6 Swift在 Xcode 6 Swift 上插入声音
【发布时间】:2014-08-09 21:12:10
【问题描述】:

有人可以帮忙告诉我将声音插入我的 xcode 6 swift 项目并让它在后台播放的代码是什么

【问题讨论】:

    标签: audio swift


    【解决方案1】:

    对于 OS X,要播放声音,您可以使用 NSSound 或更高级的东西 Core Audio

    使用 NSSound(最简单的方法),您可以将声音文件放入资产库中,然后执行以下操作:

    var sound = NSSound(named: "name_of_sound")
    sound.play()
    

    对于 iOS,请尝试以下代码:

    import UIKit
    import AVFoundation
    
    class ViewController: UIViewController {
    
    var audioPlayer = AVAudioPlayer()
    
    override func viewDidLoad() {
        super.viewDidLoad()
    
        var alertSound = NSURL(fileURLWithPath: NSBundle.mainBundle().pathForResource("sound_name", ofType: "wav"))
        println(alertSound)
    
        // Removed deprecated use of AVAudioSessionDelegate protocol
        AVAudioSession.sharedInstance().setCategory(AVAudioSessionCategoryPlayback, error: nil)
        AVAudioSession.sharedInstance().setActive(true, error: nil)
    
        var error:NSError?
        audioPlayer = AVAudioPlayer(contentsOfURL: alertSound, error: &error)
        audioPlayer.prepareToPlay()
        audioPlayer.play()
        }
    
    }
    

    一般来说,将音频播放器作为类成员似乎是个好主意

    【讨论】:

    • 它不起作用,我收到错误 - 在调用第一行代码时缺少参数“size”的参数,第二行我收到错误 - 预期声明
    • 代码没有任何问题 - 它应该可以完美运行我已经使用了很多次。你的声音是什么文件格式,你把它放在你的项目中的什么地方?例如如果你有一个 wav 声音 'alrighty.wav' 你将文件添加到你的项目中,然后使用代码 var sound = NSSound(named: "alrighty.wav")
    • 我正在使用 .wav 文件格式,并且我已将其放入我的项目中,但我仍然遇到相同的错误,我不需要像导入 SpirteKit 那样导入任何模块,但我不需要导入任何音频模块
    • 是的,对不起,我忘了提。我刚刚尝试了您给我的代码,但现在我收到错误消息 - 'GameScene.Type' 没有名为 'sound' 的成员
    • 我还得到了第 3 行代码的错误预期声明
    猜你喜欢
    • 1970-01-01
    • 2017-02-15
    • 1970-01-01
    • 1970-01-01
    • 2014-10-15
    • 1970-01-01
    • 2014-08-06
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多