Multipeer stream musique

Bonjour tout le monde,


Je souhaite streamer un fichier musical issu de la bibliothèque de l'iPhone à  l'aide de la technologie Multipeer. J'ai réussi à  faire un petit chat rapide pour tester la connexion et ça fonctionne mais maintenant je me demande comment fonctionne le streaming en multipeer. Voilà  le code que j'ai fait pour l'instant :



func mediaPicker(mediaPicker: MPMediaPickerController!, didPickMediaItems mediaItemCollection: MPMediaItemCollection!) {
self.dismissViewControllerAnimated(true, completion: nil)
println(mediaItemCollection.items[0].valueForProperty(MPMediaItemPropertyTitle))

let musicUrl: NSURL = mediaItemCollection.items[0].valueForProperty(MPMediaItemPropertyAssetURL) as NSURL
let asset: AVURLAsset = AVURLAsset(URL: musicUrl, options: nil)
let assetOutput = AVAssetReaderTrackOutput(track: asset.tracks[0] as AVAssetTrack, outputSettings: nil)
let assetReader: AVAssetReader = AVAssetReader(asset: asset, error: nil)
assetReader.addOutput(assetOutput)
assetReader.startReading()

let sampleBuffer: CMSampleBufferRef = assetOutput.copyNextSampleBuffer()

Que dois-je rajouter pour pouvoir streamer (et lancer en même temps sur mon iPhone) cette musique ?


Merci pour votre aide.


 


Je vous mets en PJ mon projet si ça peut vous aider.


Réponses

  • Personne n'a jamais utilisé cette technologie sur le forum ?


  • Salut tout le monde,


     


    J'ai passé pas mal de temps pour essayer de résoudre le problème. Voici ce que j'ai fait :



    //
    // ViewController.swift
    // Boost
    //
    // Created by Gautier Delorme on 29/12/2014.
    // Copyright (c) 2014 Gautier Delorme. All rights reserved.
    //

    import UIKit
    import MultipeerConnectivity
    import AVFoundation
    import MediaPlayer

    class ViewController: UIViewController, MCBrowserViewControllerDelegate, MCSessionDelegate, MPMediaPickerControllerDelegate, NSStreamDelegate {

    let screenSize: CGRect = UIScreen.mainScreen().bounds
    let chatView = UITextView()
    let chatTextField = UITextField()
    let browseButton = UIButton()
    let sendButton = UIButton()
    let musicButton = UIButton()

    let serviceType = "dance-party"
    var browser : MCBrowserViewController!
    var assistant : MCAdvertiserAssistant!
    var session : MCSession!
    var peerID: MCPeerID!

    override func viewDidLoad() {
    super.viewDidLoad()

    self.navigationController?.navigationBarHidden = true
    self.view.backgroundColor = UIColor.blueColor()
    chatView.frame = CGRectMake(5, 5, screenSize.width - 10, screenSize.height/2)
    chatView.editable = false
    chatView.backgroundColor = UIColor.redColor()

    chatTextField.frame = CGRectMake(5, chatView.frame.origin.y+chatView.frame.height+5, screenSize.width - screenSize.width/3, 30)
    chatTextField.backgroundColor = UIColor.grayColor()

    sendButton.frame = CGRectMake((screenSize.width*2/3)+5, chatTextField.frame.origin.y + 5, screenSize.width/3-10, 10)
    sendButton.setTitle("Send", forState: UIControlState.Normal)
    sendButton.addTarget(self, action: "sendMessage:", forControlEvents: UIControlEvents.TouchUpInside)

    browseButton.frame = CGRectMake(5, chatTextField.frame.origin.y+chatTextField.frame.height+15, 70, 10)
    browseButton.setTitle("Browse", forState: UIControlState.Normal)
    browseButton.addTarget(self, action: "showBrowser:", forControlEvents: UIControlEvents.TouchUpInside)

    musicButton.frame = CGRectMake(5, browseButton.frame.origin.y+browseButton.frame.height+15, 70, 10)
    musicButton.setTitle("Music", forState: UIControlState.Normal)
    musicButton.addTarget(self, action: "addSongs:", forControlEvents: UIControlEvents.TouchUpInside)

    self.view.addSubview(chatView)
    self.view.addSubview(chatTextField)
    self.view.addSubview(sendButton)
    self.view.addSubview(browseButton)
    self.view.addSubview(musicButton)

    self.peerID = MCPeerID(displayName: UIDevice.currentDevice().name)
    self.session = MCSession(peer: peerID)
    self.session.delegate = self

    // create the browser viewcontroller with a unique service name
    self.browser = MCBrowserViewController(serviceType:serviceType,
    session:self.session)

    self.browser.delegate = self

    self.assistant = MCAdvertiserAssistant(serviceType:serviceType,
    discoveryInfo:nil, session:self.session)

    // tell the assistant to start advertising our fabulous chat
    self.assistant.start()
    }

    func sendMessage(sender:UIButton!) {
    // Bundle up the text in the message field, and send it off to all
    // connected peers

    let msg = self.chatTextField.text.dataUsingEncoding(NSUTF8StringEncoding,
    allowLossyConversion: false)

    var error : NSError?

    self.session.sendData(msg, toPeers: self.session.connectedPeers,
    withMode: MCSessionSendDataMode.Unreliable, error: &error)

    if error != nil {
    print("Error sending data: \(error?.localizedDescription)")
    }

    self.updateChat(self.chatTextField.text, fromPeer: self.peerID)

    self.chatTextField.text = ""
    }

    func showBrowser(sender:UIButton!) {
    // Show the browser view controller
    self.presentViewController(self.browser, animated: true, completion: nil)
    }

    func addSongs(sender:UIButton!) {
    let picker = MPMediaPickerController(mediaTypes: MPMediaType.Music);
    picker.delegate = self
    self.presentViewController(picker, animated: true, completion: nil)
    }

    func mediaPicker(mediaPicker: MPMediaPickerController!, didPickMediaItems mediaItemCollection: MPMediaItemCollection!) {
    self.dismissViewControllerAnimated(true, completion: nil)
    println(mediaItemCollection.items[0].valueForProperty(MPMediaItemPropertyTitle))

    let musicUrl: NSURL = mediaItemCollection.items[0].valueForProperty(MPMediaItemPropertyAssetURL) as NSURL
    let asset: AVURLAsset = AVURLAsset(URL: musicUrl, options: nil)
    let assetOutput = AVAssetReaderTrackOutput(track: asset.tracks[0] as AVAssetTrack, outputSettings: nil)

    var error : NSError?
    println("yo0")
    let assetReader: AVAssetReader = AVAssetReader(asset: asset, error: &error)

    if error != nil {
    print("Error asset Reader: \(error?.localizedDescription)")
    }

    assetReader.addOutput(assetOutput)
    assetReader.startReading()

    let sampleBuffer: CMSampleBufferRef = assetOutput.copyNextSampleBuffer()

    var audioBufferList = AudioBufferList(mNumberBuffers: 1, mBuffers: AudioBuffer(mNumberChannels: 0, mDataByteSize: 0, mData: nil))
    var blockBuffer: Unmanaged<CMBlockBuffer>? = nil

    CMSampleBufferGetAudioBufferListWithRetainedBlockBuffer(
    sampleBuffer,
    nil,
    &audioBufferList,
    UInt(sizeof(audioBufferList.dynamicType)),
    nil,
    nil,
    UInt32(kCMSampleBufferFlag_AudioBufferList_Assure16ByteAlignment),
    &blockBuffer
    )
    let stream = session.startStreamWithName("music", toPeer: session.connectedPeers[0] as MCPeerID, error: &error)

    if error != nil {
    print("Error stream: \(error?.localizedDescription)")
    }

    for (var i :UInt32 = 0; i < audioBufferList.mNumberBuffers; i++) {
    var audioBuffer = AudioBuffer(mNumberChannels: audioBufferList.mBuffers.mNumberChannels, mDataByteSize: audioBufferList.mBuffers.mDataByteSize, mData: audioBufferList.mBuffers.mData)
    stream.write(UnsafeMutablePointer<UInt8>(audioBuffer.mData), maxLength: Int(audioBuffer.mDataByteSize))
    }
    }

    func updateChat(text : String, fromPeer peerID: MCPeerID) {
    // Appends some text to the chat view

    // If this peer ID is the local device's peer ID, then show the name
    // as "Me"
    var name : String

    switch peerID {
    case self.peerID:
    name = "Me"
    default:
    name = peerID.displayName
    }

    // Add the name to the message and display it
    let message = "\(name): \(text)\n"
    self.chatView.text = self.chatView.text + message
    }

    func browserViewControllerDidFinish(
    browserViewController: MCBrowserViewController!) {
    // Called when the browser view controller is dismissed (ie the Done
    // button was tapped)

    self.dismissViewControllerAnimated(true, completion: nil)
    }

    func browserViewControllerWasCancelled(
    browserViewController: MCBrowserViewController!) {
    // Called when the browser view controller is cancelled

    self.dismissViewControllerAnimated(true, completion: nil)
    }

    func session(session: MCSession!, didReceiveData data: NSData!,
    fromPeer peerID: MCPeerID!) {
    // Called when a peer sends an NSData to us

    // This needs to run on the main queue
    dispatch_async(dispatch_get_main_queue()) {
    var msg = NSString(data: data, encoding: NSUTF8StringEncoding)
    self.updateChat(msg!, fromPeer: peerID)
    }
    }

    // The following methods do nothing, but the MCSessionDelegate protocol
    // requires that we implement them.
    func session(session: MCSession!,
    didStartReceivingResourceWithName resourceName: String!,
    fromPeer peerID: MCPeerID!, withProgress progress: NSProgress!) {

    // Called when a peer starts sending a file to us
    }

    func session(session: MCSession!,
    didFinishReceivingResourceWithName resourceName: String!,
    fromPeer peerID: MCPeerID!,
    atURL localURL: NSURL!, withError error: NSError!) {
    // Called when a file has finished transferring from another peer
    }

    func session(session: MCSession!, didReceiveStream stream: NSInputStream!,
    withName streamName: String!, fromPeer peerID: MCPeerID!) {
    // Called when a peer establishes a stream with us
    if streamName == "music" {
    stream.delegate = self
    stream.scheduleInRunLoop(NSRunLoop.currentRunLoop(), forMode: NSDefaultRunLoopMode)
    stream.open()
    }
    }

    func stream(aStream: NSStream, handleEvent eventCode: NSStreamEvent) {
    if eventCode == NSStreamEvent.HasBytesAvailable {

    } else if eventCode == NSStreamEvent.EndEncountered {

    } else if eventCode == NSStreamEvent.ErrorOccurred {

    }
    }

    func session(session: MCSession!, peer peerID: MCPeerID!,
    didChangeState state: MCSessionState) {
    // Called when a connected peer changes state (for example, goes offline)

    }


    override func didReceiveMemoryWarning() {
    super.didReceiveMemoryWarning()
    // Dispose of any resources that can be recreated.
    }
    }


    Pour l'appli "invitée" (celle qui devra jouer la musique) j'utilise celle là  http://robots.thoughtbot.com/streaming-audio-to-multiple-listeners-via-ios-multipeer-connectivity (car c'est cet article que j'ai suivi) mais ça ne fonctionne pas et je n'ai aucune erreur d'affichée. Pouvez-vous voir mes erreurs ?


    (Ne regardez pas l'interface, j'ai commencé par une app de chat pour tester la connexion et ça fonctionne bien)


     


    Merci pour votre aide. :)


Connectez-vous ou Inscrivez-vous pour répondre.