如何在Singleton方法中实现AVAudioPlayer?

时间:2015-12-23 12:08:44

标签: ios swift singleton swift2 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,但我无法实现它。

键入时让audioPlayer:AVAudio - >它没有显示任何东西。

2 个答案:

答案 0 :(得分:2)

至于你案例中的单身部分(来自评论)你应该使用这样的东西:

MyAudioPlayer.playFile("Breach", type: "mp3")

用法是:

loaders: [{
        test: /\.jsx?$/,
        loader: 'babel',
        query: {
            presets: ['es2015', 'react']
        }
    }]

答案 1 :(得分:1)

这并不是很有意义,但这可以为我编译:

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。其他一些语法也失败了。

在Swift BTW中没有以这种方式使用单例。

<强>用法:

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