从 URI 获取音频流并在 iPhone 上播放 [英] Get an audio stream from URI and play it on iPhone
问题描述
我想从 URL 获取音频流并在 iPhone 上播放.不幸的是,只有如何播放该流的 C# 示例,但我需要在 iPhone 框架中的 Objective C 上实现.我尝试过自己使用不同的音频框架,但都没有成功.这是 C# 中的内容:
I would like to get an audio stream from URL and play it on iPhone. Unfortunately, there is only C# example of how to play that stream, but I need a realization on Objective C in iPhone frameworks. I have tried my self to use different audio frameworks but it was all unsuccessful. This is what in C#:
response = httpWebRequest.GetResponse();
using (Stream stream = response.GetResponseStream())
{
using (SoundPlayer player = new SoundPlayer(stream))
{
player.PlaySync();
}
}
在目标 C 中我应该怎么做才能从该 url 获取流音频?在那个 URL 中,我没有 mp3 文件或其他东西,我只是得到一个流.可能我必须以某种方式将该流下载到 iPhone 音频文件,然后播放它以消除延迟.
What should I do in objective C to get a stream audio from that url? In that URL I don't have an mp3 file or something, I just get a stream. Probably I must somehow download that stream to an iPhone audio file and then play it to get rid of lags.
我试过这个:
AVPlayer *player = [AVPlayer playerWithURL:url];
[player play];
还有这个:
AVAudioPlayer *theAudio = [[AVAudioPlayer alloc] initWithContentsOfURL: url error:nil];
[theAudio setVolume :0.50]; //setting the volume
[theAudio play];
都没有奏效.我已经测试了我的网址,它在浏览器中运行良好.
Neither worked. I have tested my url, it works well in browser.
这是有效的代码:
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];
这篇关于从 URI 获取音频流并在 iPhone 上播放的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!