0

This is my code

 NSURL *url = [NSURL URLWithString:recentActivity.url];
 NSData *data = [NSData dataWithContentsOfURL:url];
 AVAudioPlayer *audioPlayer = [[AVAudioPlayer alloc] initWithData:data error:nil];
 [audioPlayer play];

and it's not playing audio

Zee
  • 1,865
  • 21
  • 42
  • i have tried this, but not working. – Harimohan Agrawal Jan 19 '18 at 05:46
  • did you try with different urls – Prashant Tukadiya Jan 19 '18 at 05:48
  • yes sir, i use, "https://www.soundhelix.com/examples/mp3/SoundHelix-Song-2.mp3" – Harimohan Agrawal Jan 19 '18 at 05:52
  • But sir, NSURL *url = [NSURL URLWithString:recentActivity.url]; //Add any link of audio file which you want to play playerItem = [AVPlayerItem playerItemWithURL:[NSURL URLWithString:recentActivity.url]]; // add url to playerItem player = [AVPlayer playerWithPlayerItem:playerItem]; // add player item to AVAudioPlayer player = [AVPlayer playerWithURL:url]; [player play]; Using this its works. Thanks. – Harimohan Agrawal Jan 19 '18 at 05:55

3 Answers3

0

Try this. It will work fine.

NSURL *url = [NSURL URLWithString:url];    
self.avAsset = [AVURLAsset URLAssetWithURL:url options:nil];    
self.playerItem = [AVPlayerItem playerItemWithAsset:avAsset];    
self.audioPlayer = [AVPlayer playerWithPlayerItem:playerItem];    
[self.audioPlayer play];

For Swift 3.0

var player: AVAudioPlayer!
var slider: UISlider!

@IBAction func play(_ sender: Any) {
    var url = URL(fileURLWithPath: Bundle.main.path(forResource: "sound", ofType: ".mp3")!)
    var error: Error?
    do {
        player = try AVAudioPlayer(contentsOf: url)
    }
    catch let error {
    }
    if player == nil {
        print("Error: \(error)")
    }
    player.prepareToPlay()
    slider.maximumValue = Float(player.duration)
    slider.value = 0.0
    Timer.scheduledTimer(timeInterval: 1.0, target: self, selector: #selector(self.updateTime), userInfo: nil, repeats: true)
    player.play()
}

func updateTime(_ timer: Timer) {
    slider.value = Float(player.currentTime)
}

@IBAction func slide(_ slider: UISlider) {
    player.currentTime = TimeInterval(slider.value)
}
Dixit Akabari
  • 2,419
  • 13
  • 26
0

You can try this small piece of code to play audio from an URL

Create a new helper calls and add the following code to PlayerHelper.h

    @interface PlayerHelper : NSObject
{
    AVPlayer *player;
}

+ (PlayerHelper*)shared;

- (BOOL)playAudio:(NSString*)urlPath;

- (void)stopPlayer;

- (void)pausePlayer;

- (void)seekTo:(float)time;

- (float)duration;
@end

Add following code to PlayerHelper.m file

 #import "PlayerHelper.h"

@implementation PlayerHelper
+ (PlayerHelper*)shared{
    static PlayerHelper *helper = nil;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        helper = [[PlayerHelper alloc] init];
    });
    return helper;
}

- (void)stopPlayer{
    if (player != nil) {
        player = nil;
    }
}

- (void)pausePlayer{
    [player pause];
}

- (BOOL)playAudio:(NSString*)urlPath{
    NSURL *URL = [NSURL URLWithString:urlPath];
    NSError *error = nil;
    if (player == nil){
        player = [[AVPlayer alloc] initWithURL:URL];
    }
    if (error == nil) {
        [player play];
        return TRUE;
    }
    NSLog(@"error %@",error);
    return FALSE;
}

- (void)seekTo:(float)time{
    [player seekToTime:CMTimeMake(time, 1)];
}

- (float)duration{
    return player.currentTime.value;
    return 0;
}
@end

Usage,

NSString *url = @"https://isongs/media/rapon.mp3";
[[PlayerHelper shared] playAudio:url];
Jayachandra A
  • 1,335
  • 1
  • 10
  • 21
0

The problem with your code (assuming that you're using ARC) is that you're allocating AVAudioPlayer and then you send play message but as soon as your method returns the ARC deallocates the AVAudioPlayer and hence you won't be able to listen any sound. To resolve this issue please retain your AVAudioPlayer instance either in an ivar or in some property. Below is the example of an ivar

@implementation ViewController {
  AVAudioPlayer *audioPlayer;
}

- (void)viewDidLoad {
  [super viewDidLoad];
  NSURL *url = [NSURL URLWithString:@"https://www.soundhelix.com/examples/mp3/SoundHelix-Song-2.mp3"];
  NSData *data = [NSData dataWithContentsOfURL:url];
  audioPlayer = [[AVAudioPlayer alloc] initWithData:data error:nil]; // Now we are assigning it in an instance variable thus ARC will not deallocate it.
  [audioPlayer play];
}


@end
Inder Kumar Rathore
  • 39,458
  • 17
  • 135
  • 184