Search code examples
iosobjective-ciphoneswiftcore-audio

How i can play [UInt8] audio stream?


I am connected to the server via TCP / IP and receives [UInt8]. I know that it is the audio. How to play the stream on the iPhone?

@IBAction func connectAndListen(sender: AnyObject) {
    var client:TCPClient = TCPClient(addr: "80.233.248.96", port: 6969)
    var (success,errmsg)=client.connect(timeout: 1)
    if success{
        while (success){
            var (success,errmsg)=client.send(str:"GET / HTTP/1.0\n\n" )
            if success{
                var data = client.read(1024*10)
                if let d = data{

                    var endMarker = NSMutableData(bytes: d, length: d.count)
                    println(endMarker)
                    self.audioPlayer = AVAudioPlayer(data: endMarker, error: nil)

                    self.audioPlayer?.prepareToPlay()
                    self.audioPlayer?.play()

                }
            }else{
                println(errmsg)
                break
            }
        }
    }else{
        println(errmsg)
    }
}

my Crash:

fatal error: unexpectedly found nil while unwrapping an Optional value

on this self.audioPlayer!.prepareToPlay() Print screen my crash


Solution

    1. Create an NSData object from the bytes in your stream.
    2. Create an AVAudioPlayer using the initWithData:error: method.
    3. Play the audio using the AVAudioPlayer play method.

    I cannot tell you exactly how to create the NSData object, because I don't know how you get your byte stream, but the NSData class is well documented in the Apple documentation.