从URI获取audiostream并在iPhone上播放

我想从URL获取audiostream并在iPhone上播放。 不幸的是,只有C#的例子,如何播放stream,但我需要在iPhone框架中的目标C实现。 我尝试过使用不同的audio框架,但都不成功。 这是什么在C#中:

response = httpWebRequest.GetResponse(); using (Stream stream = response.GetResponseStream()) { using (SoundPlayer player = new SoundPlayer(stream)) { player.PlaySync(); } } 

我应该在目标C做什么,以获得来自该url的streamaudio? 在那个url中,我没有mp3文件或者其他东西,我只是得到一个stream。 也许我必须以某种方式下载该stream到iPhoneaudio文件,然后播放它来摆脱滞后。

我试过这个:

  AVPlayer *player = [AVPlayer playerWithURL:url]; [player play]; 

和这个:

 AVAudioPlayer *theAudio = [[AVAudioPlayer alloc] initWithContentsOfURL: url error:nil]; [theAudio setVolume :0.50]; //setting the volume [theAudio play]; 

都没有工作。 我testing了我的url,它在浏览器中运行良好。

这是工作的代码:

 NSData *_objectData = [NSData dataWithContentsOfURL:url]; NSError *error; AVAudioPlayer *audioPlayer = [[AVAudioPlayer alloc] initWithData:_objectData error:&error]; audioPlayer.numberOfLoops = 0; audioPlayer.volume = 1.0f; [audioPlayer prepareToPlay]; if (audioPlayer == nil) NSLog(@"%@", [error description]); else [audioPlayer play]; 

 NSString* resourcePath = url; //your url NSData *_objectData = [NSData dataWithContentsOfURL:[NSURL URLWithString:resourcePath]]; NSError *error; app.audioPlayer = [[AVAudioPlayer alloc] initWithData:_objectData error:&error]; app.audioPlayer.numberOfLoops = 0; app.audioPlayer.volume = 1.0f; [app.audioPlayer prepareToPlay]; if (app.audioPlayer == nil) NSLog(@"%@", [error description]); else [app.audioPlayer play]; 

嘿,我面对这个无线电应用程序的audiostream的问题。 我曾经寻找答案,但他们没有工作。 AVAudioPlayer不是在这里使用的类。 使用NSData对象下载URL的内容不是解决scheme,因为它下载内容,然后代码进一步执行。 这类似于下载一个MP3,然后在播放器上本地播放。

 [NSData dataWithContentsOfURL:[NSURL URLWithString:resourcePath]]; //Downloads the contents of the url and in case of radio the url's content is unlimited. The program gets frozen on executing this. 

而是使用AVPlayer类。

这个代码在我的广播应用程序中工作

 AVPlayer *objAVPlayer = [[AVPlayer alloc] initWithURL:url]; [objAVPlayer play]; 

此代码不会在url处下载内容,但会在收到stream时播放该stream。

查看AVPlayer类,这是AVFoundation框架的一部分…这是您用于stream式audio的objective-c(iOS)类。

 MPMoviePlayerController *player; player = [[MPMoviePlayerController alloc] init] ; player.view.frame = CGRectMake(0, 0, 0, 0); player.movieSourceType = MPMovieSourceTypeStreaming; player.view.hidden = YES; [self.view addSubview: [wikiMusicPlayer view]]; NSString *address = Your URL; address = [address stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]; NSURL *url = [NSURL URLWithString:address]; [wikiMusicPlayer setContentURL:url]; [wikiMusicPlayer prepareToPlay]; [wikiMusicPlayer setShouldAutoplay: NO]; [wikiMusicPlayer play];