How to play a music file using URL link in iPhone?

后端 未结 5 729
无人共我
无人共我 2020-12-13 05:12

I want to play a music file using URL Link in the iPhone. But when I use the below code I am getting error I am not getting where I am going wrong. Can anyone Correct me?

相关标签:
5条回答
  • 2020-12-13 05:42

    Try the following:

    -(void)viewDidLoad 
    
    {
    
    [super viewDidLoad];
    NSString* resourcePath = @"your url"; //your url
    
    NSData *_objectData = [NSData dataWithContentsOfURL:[NSURL URLWithString:resourcePath]];
    NSError *error;
    
    
    audioPlayer = [[AVAudioPlayer alloc] initWithData:_objectData error:&error];
    audioPlayer.numberOfLoops = 1;
    
    if (audioPlayer == nil)
        NSLog([error description]);             
    
    else 
        [audioPlayer play];
    
    0 讨论(0)
  • 2020-12-13 05:43

    I guess you are sending

    audioPlayer.numberOfLoops = -1;
    

    to receive NSInvalidArgumentException change it to

    audioPlayer.numberOfLoops = 1;
    

    and check apple's documentation here

    0 讨论(0)
  • 2020-12-13 05:44

    Try my code:

    NSURL *filepath = [NSURL fileURLWithPath:audioFilePath];
     [yourMediaPlayer setContentURL:filepath];
      //set player.
      yourMediaPlayer.controlStyle = MPMovieControlStyleNone;
      yourMediaPlayer.currentPlaybackTime = 0;
      yourMediaPlayer.shouldAutoplay = FALSE;
    
      [yourMediaPlayer play];
    

    ^-^,I use MPMoviePlayerController with above code.

    0 讨论(0)
  • 2020-12-13 05:45

    This should work:

    NSURL *url = [NSURL URLWithString:@"<#Live stream URL#>];
    
    // You may find a test stream at <http://devimages.apple.com/iphone/samples/bipbop/bipbopall.m3u8>.
    
    self.playerItem = [AVPlayerItem playerItemWithURL:url];
    
    //(optional) [playerItem addObserver:self forKeyPath:@"status" options:0 context:&ItemStatusContext];
    
    self.player = [AVPlayer playerWithPlayerItem:playerItem];
    
    self.player = [AVPlayer playerWithURL:<#Live stream URL#>];
    
    //(optional) [player addObserver:self forKeyPath:@"status" options:0 context:&PlayerStatusContext];
    

    Use the following code to play the music:

    [self.player play];

    0 讨论(0)
  • 2020-12-13 05:59

    Current Answer:

    Now consider Why does AVAudioPlayer initWithContentsOfURL always fail with error code=-43 link. its solution is avplayer link

    Earlier Answer

    //You have to pass NSURL not NSData
     NSString* resourcePath = @"http://192.167.1.104:8888/SHREYA.mp3"; //your url
     NSURL *url = [NSURL alloc]initWithString:resourcePath];
     audioPlayer = [[AVAudioPlayer alloc] initWithURL:url error:&error];
    
     audioPlayer.delegate = self;
     [url release];
    
     [audioPlayer prepareToPlay];
     [audioPlayer play];
    
    0 讨论(0)
提交回复
热议问题