Very short snippet: streaming mp3 file su Apple iPhone

Un’alternativa davvero semplice per eseguire uno streaming di un file mp3 su Apple iPhone potrebbe essere:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
// Utilizzare AVFoundation Framework e nell'header file (.h) aggiungere
// #import <AVFoundation/AVFoundation.h>

// Nell'implementazione
// inserite l'url del file mp3
NSString * soundFilePath = @"http://www.server.com/test.mp3";

NSURL * fileURL = [NSURL URLWithString:soundFilePath]
NSURLRequest * request = [NSURLRequest requestWithURL:fileURL];
NSData *dataRaw = [NSURLConnection sendSynchronousRequest:request returningResponse:nil error:nil];

AVAudioPlayer * audioPlayer = [[AVAudioPlayer alloc] initWithData:dataRaw error:nil];

[audioPlayer play];

Ora, non direttamente correlato a questo “snippet”, guardate come è facile con la (tanto odiata) sintassi a parentesi quadre di Objective-c ridurre tutto ad una sola riga:

1
2
AVAudioPlayer * audioPlayer = [[AVAudioPlayer alloc] initWithData: [NSURLConnection sendSynchronousRequest:[NSURLRequest requestWithURL: [NSURL URLWithString: @"http://www.server.com/test.mp3" ] ] returningResponse:nil error:nil] error:nil];
[audioPlayer play];

Indentando il codice un po’ meglio si ha:

1
2
3
4
5
6
7
8
9
10
AVAudioPlayer * audioPlayer =
    [
        [AVAudioPlayer alloc]
            initWithData: [NSURLConnection
                sendSynchronousRequest:[NSURLRequest
                    requestWithURL: [NSURL URLWithString: @"http://www.server.com/test.mp3" ]
                ]
            returningResponse:nil error:nil]
            error:nil];
[audioPlayer play];

Questione di gusti, ovviamente…

Non ci sono commenti per questo Post

Lascia un commento

TAG XHTML PERMESSI: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong> INSERIMENTO CODICE:
<pre></pre> // blocco generico
					<code></code> // blocco generico
					[cc_actionscript][/cc_actionscript] // Actionscript
					[cc_actionscript3][/cc_actionscript3] // Actionscript 3
					[cc_css][/cc_css] // CSS Style Sheet
					[cc_html][/cc_html] // HTML
					[cc_js][/cc_js] // Javascript
					[cc_objc][/cc_objc] // Objective-C
					[cc_php][/cc_objc] // PHP
					[cc_sql][/cc_sql] // SQL


Stop SOPA