Stream Audio with AVPlayer

2019-04-11 03:26发布

问题:

I'm trying to play audio from a URL using AVPlayer when a row is selected in a table view but it doesn't play. What am I doing wrong?

Here is the code:

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    NSString *streamingString = [NSString stringWithFormat:@"%@.json?client_id=fc886d005e29ba78f046e5474e3fdefb", [streamURLArray objectAtIndex:indexPath.row]];
    NSURL *streamingURL = [NSURL URLWithString:streamingString];
    NSLog(@"%@", streamingURL);
    AVPlayer *player = [AVPlayer playerWithURL:streamingURL];
    [player play];
    player.actionAtItemEnd = AVPlayerActionAtItemEndNone;
}

An example of streamingURL when I log it is this.

http://api.soundcloud.com/tracks/146814101/stream.json?client_id=fc886d005e29ba78f046e5474e3fdefb

回答1:

declare AVAudioPlayer globally in your .h file

like this AVPlayer *player;

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    NSString *streamingString = [NSString stringWithFormat:@"%@.json?client_id=fc886d005e29ba78f046e5474e3fdefb", [streamURLArray objectAtIndex:indexPath.row]];
    NSURL *streamingURL = [NSURL URLWithString:streamingString];
    NSLog(@"%@", streamingURL);
    player = [AVPlayer playerWithURL:streamingURL];
    [player play];
    player.actionAtItemEnd = AVPlayerActionAtItemEndNone;
}


回答2:

You'll find numerous audio streaming kit all around GitHub.

https://github.com/tumtumtum/StreamingKit

https://github.com/muhku/FreeStreamer

https://github.com/mattgallagher/AudioStreamer



回答3:

call this method

[player prepareToPlay];

before calling

[player play];

It may help to u.