如何在Singleton方法内部实现AVAudioPlayer? [英] How to implement AVAudioPlayer Inside Singleton Method?

查看:162
本文介绍了如何在Singleton方法内部实现AVAudioPlayer?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是我的代码:

class SomeAudioManager: NSObject
{

    class var sharedInstance: SomeAudioManager{
        struct Static {
            static var onceToken: dispatch_once_t = 0
            static var instance: SomeAudioManager? = nil
        }
        dispatch_once(&Static.onceToken) {
            Static.instance = SomeAudioManager()
        }
        return Static.instance!
    }
    func audioView(songname: NSString,format: NSString)
    {
        let audioPlayer:ava
        audioPlayer=try AVAudioPlayer(contentsOfURL: NSURL(fileURLWithPath: NSBundle.mainBundle().pathForResource(songname, ofType:format)!), fileTypeHint: AVFileTypeMPEGLayer3)
        audioPlayer!.delegate=self;
        self.audioPlayer!.play()
    }
}

该AVAudioPlayer在NSObject下,但我无法实现.

That AVAudioPlayer is under NSObject but I can't implement it.

在键入让audioPlayer:AVAudio->时,它什么也没显示.

While typing let audioPlayer:AVAudio -> it didn't display anything.

推荐答案

不是很有意义,但这对我来说是编译的:

Not that it makes much sense but this compiles for me:

import AVFoundation
class SomeAudioManager: NSObject, AVAudioPlayerDelegate
{
    class var sharedInstance: SomeAudioManager {
        struct Static {
            static var onceToken: dispatch_once_t = 0
            static var instance: SomeAudioManager? = nil
        }
        dispatch_once(&Static.onceToken) {
            Static.instance = SomeAudioManager()
        }
        return Static.instance!
    }
    func audioView(songname: String,format: String) {
        let audioPlayer: AVAudioPlayer

        do {
            audioPlayer = try AVAudioPlayer(contentsOfURL: NSURL(fileURLWithPath: NSBundle.mainBundle().pathForResource(songname, ofType:format)!), fileTypeHint: AVFileTypeMPEGLayer3)
            audioPlayer.delegate = self;
            audioPlayer.play()
        } catch {
            // error
        }
    }
}

因此,您需要导入框架,swift中的try-catch是do-try-catch.其他一些语法失败也已修复.

So you need to import the framework, try-catch in swift are do-try-catch. Some other syntax fails are fixed as well.

在Swift BTW中不以这种方式使用单例.

The singleton is not used this way in Swift BTW.

用法:

class someOtherClass {
    func doSomething() {
        SomeAudioManager().audioView("name_here", format: "format_here")
        SomeAudioManager.sharedInstance.audioView("name_here", format: "format_here")
    }
}

这篇关于如何在Singleton方法内部实现AVAudioPlayer?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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