简体   繁体   中英

Stream Audio with AVPlayer

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

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

call this method

[player prepareToPlay];

before calling

[player play];

It may help to u.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM