Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
283 views
in Technique[技术] by (71.8m points)

ios - Get an audio stream from URI and play it on iPhone

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();
                }
            }

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.

I tried this:

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

And this:

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.

This is the code that worked:

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];
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)
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];

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...