How to play m3u audio stream in iOS app

2019-01-26 21:36发布

问题:

I'm trying to create an iOS/iPhone radio app using Xcode 4.5.2.

I wanted to stream @"http://xx.xxxxxxx.com/8111/radio.m3u" with play, pause, volume control and able to play on background feature/multitasking.

I've added AVFoundation, Mediaplayer and AudioToolBox frameworks thus far. I've added play, pause and slider objects to xib.

ViewController.h

@interface ViewController : UIViewController

@property (strong,nonatomic) MPMoviePlayerController *myPlayer;

@property (weak, nonatomic) IBOutlet UISlider *myslider;

- (IBAction)playButtonPressed;

- (IBAction)myslider:(id)sender;

@end

ViewController.m
#import "ViewController.h"
#import <MediaPlayer/MediaPlayer.h>

@interface ViewController ()
{
    UISlider *volumeSlider;
}

@end

@implementation ViewController

- (void)viewDidLoad
{
    [super viewDidLoad];
    [[UIApplication sharedApplication] beginReceivingRemoteControlEvents];
    UIBackgroundTaskIdentifier newTaskId = UIBackgroundTaskInvalid;
    newTaskId = [[UIApplication sharedApplication] beginBackgroundTaskWithExpirationHandler:NULL];
}

- (IBAction)playButtonPressed;
{
    NSString *urlAddress = @"http://xxxxxxx.com/8111/listen.m3u";
    NSURL *url = [NSURL URLWithString:urlAddress];
    MPMoviePlayerController *player = [[MPMoviePlayerController alloc]initWithContentURL:url];
    player.movieSourceType = MPMovieSourceTypeStreaming;
    [player prepareToPlay];
    self.myPlayer = player;
    [self.view addSubview:self.myPlayer.view];
    [self.myPlayer play];
}

- (IBAction)stopButtonPressed;
{
    [self.myPlayer stop];
}
- (IBAction)myslider:(id)sender
{
    MPVolumeView *volumeView = [[MPVolumeView alloc] initWithFrame: CGRectMake(10, 10, 200, 40)];
    [volumeSlider addSubview:volumeView];
    [volumeView sizeToFit];
    }

回答1:

There are Two way to achieve this.

  1. You can directly load you URL in UIWebView and it will properly.
  2. You can also use MPMoviePlayerController.


回答2:

Create a "MPMoviePlayerController *player" as a strong object in your ViewController.

So you code would look something like below:

@interface ViewController ()
{
    UISlider *volumeSlider;
    MPMoviePlayerController *player;
}

@end


- (IBAction)playButtonPressed;
{
    NSString *urlAddress = @"http://xxxxxxx.com/8111/listen.m3u";
    NSURL *url = [NSURL URLWithString:urlAddress];

    if(nil != player)
    {
      player = nil; // Alternatively you can stop and restart with the different stream.
    }

    player = [[MPMoviePlayerController alloc]initWithContentURL:url];
    player.movieSourceType = MPMovieSourceTypeStreaming;
    [player prepareToPlay];
    self.myPlayer = player;
    [self.view addSubview:self.myPlayer.view];
    [self.myPlayer play];
}