Objective-C Simple Music Player

Keywords: github network iOS

AVAudio Player is mostly used for music broadcasting in Objective-C. It has many advantages:
(1) Music of any length can be played;
(2) It can be played circularly;
(3) The playing time can be controlled;
(4) The volume of the vocal tract can be controlled to achieve stereo effect;
(5) The volume can be adjusted.  
But AVAudio Player has a big disadvantage, that is, it can only play local audio, network resources must be loaded before playing, can not play immediately; but the system provides us with another more abundant class MPMovie Player Controller and AVPlayer to play streaming media. MPMovie Player Controller is simpler to use, but its function is not as powerful as AVPlayer. Here we introduce AVPlayer to play online audio and video later. Direct to the code, comments will try to write more detailed:
Create a new class that inherits from NSObject: AudioPlayer
h file code:

#import <Foundation/Foundation.h>
@class AudioPlayer;

@protocol AudioPlayerDelegate <NSObject>

//Events executed per second in playback
- (void)audioplayerPlayWith:(AudioPlayer *)audioplayer Progress:(float)progress;

//Perform this event when a song is played
- (void)audioplayerDidFinishItem:(AudioPlayer *)audioplayer;

@end


@interface AudioPlayer : NSObject


@property(nonatomic,assign)id<AudioPlayerDelegate>delegate;
@property(nonatomic,assign)BOOL isPlaying;
+(AudioPlayer*)sharePlayer;
-(void)play;
-(void)pause;
-(void)seekToTime:(float)time;
-(void)setPrepareMusicUrl:(NSString*)urlStr;
@end
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25

m file code:

#import "AudioPlayer.h"
@import AVFoundation;
@interface AudioPlayer ()
{
    BOOL _isPrepare;//Are you ready to play successfully?
    BOOL _isPlaying;//Is the player playing?
}

@property(nonatomic,strong)AVPlayer *player;
@property(nonatomic,strong)NSTimer *timer;

@end
@implementation AudioPlayer

+(AudioPlayer*)sharePlayer
{

    static AudioPlayer *player = nil;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        player = [AudioPlayer new];
    });
    return  player;
}
- (instancetype)init
{
    self = [super init];
    if (self) {
        //Notification Center
        [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(endAction:) name:AVPlayerItemDidPlayToEndTimeNotification object:nil];
    }
    return self;
}

-(void)setPrepareMusicUrl:(NSString*)urlStr
{

    if (self.player.currentItem) {
        [self.player.currentItem removeObserver:self forKeyPath:@"status"];
    }

//Create an item resource
    AVPlayerItem *item = [AVPlayerItem playerItemWithURL:[NSURL URLWithString:urlStr]];
    [item addObserver:self forKeyPath:@"status" options:(NSKeyValueObservingOptionNew|NSKeyValueObservingOptionOld) context:nil];
    [self.player replaceCurrentItemWithPlayerItem:item];
}

-(void)play
{
//Determine whether resources are ready to succeed
    if (!_isPrepare) {
        return;
    }
    [self.player play];
    _isPlaying = YES;
    //Picture rotation during playback
    //timer initialization
    if (_timer) {
        return;
    }

    //Create a timer
    self.timer = [NSTimer scheduledTimerWithTimeInterval:0.1 target:self selector:@selector(playingAction:) userInfo:nil repeats:YES];


}
-(void)pause
{
    if (!_isPlaying) {
        return;
    }

    [self.player pause];
    _isPlaying = NO;
    //Destroy timers
    [_timer invalidate];
    _timer = nil;

}

-(void)seekToTime:(float)time
{

//When the time of the music player changes, pause before play
    [self pause];
    [self.player seekToTime:CMTimeMakeWithSeconds(time, self.player.currentTime.timescale) completionHandler:^(BOOL finished) {
        if (finished) {
            [self play];
        }
    }];

}
//Execute this event every 0.1 seconds
-(void)playingAction:(id)sender
{


    if (self.delegate&&[self.delegate respondsToSelector:@selector(audioplayerPlayWith:Progress:)]) {

        //Get the current playing time of the song
        float progress = 1.0 * self.player.currentTime.value / self.player.currentTime.timescale;
        [self.delegate audioplayerPlayWith:self Progress:progress];


    }

}
-(void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context
{

    AVPlayerStatus staute = [change[@"new"] integerValue];
    switch (staute) {
        case AVPlayerStatusReadyToPlay:
            NSLog(@"Load successful,It's ready to play.");
            _isPrepare = YES;
            [self play];
            break;
            case AVPlayerStatusFailed:
            NSLog(@"Failed to load");
            break;
            case AVPlayerStatusUnknown:
            NSLog(@"No resources found");
            break;


        default:
            break;
    }

    NSLog(@"change:%@",change);
}
//When a song is played, the following method is performed
-(void)endAction:(NSNotification *)not
{

    if (self.delegate &&[self.delegate respondsToSelector:@selector(audioplayerDidFinishItem:)]) {
        [self.delegate audioplayerDidFinishItem:self];
    }

}

-(AVPlayer*)player
{
    if (_player==nil) {
        _player = [AVPlayer new];
    }
    return _player;
}

-(BOOL)isPlaying{
    return _isPlaying;
}
@end
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
  • 38
  • 39
  • 40
  • 41
  • 42
  • 43
  • 44
  • 45
  • 46
  • 47
  • 48
  • 49
  • 50
  • 51
  • 52
  • 53
  • 54
  • 55
  • 56
  • 57
  • 58
  • 59
  • 60
  • 61
  • 62
  • 63
  • 64
  • 65
  • 66
  • 67
  • 68
  • 69
  • 70
  • 71
  • 72
  • 73
  • 74
  • 75
  • 76
  • 77
  • 78
  • 79
  • 80
  • 81
  • 82
  • 83
  • 84
  • 85
  • 86
  • 87
  • 88
  • 89
  • 90
  • 91
  • 92
  • 93
  • 94
  • 95
  • 96
  • 97
  • 98
  • 99
  • 100
  • 101
  • 102
  • 103
  • 104
  • 105
  • 106
  • 107
  • 108
  • 109
  • 110
  • 111
  • 112
  • 113
  • 114
  • 115
  • 116
  • 117
  • 118
  • 119
  • 120
  • 121
  • 122
  • 123
  • 124
  • 125
  • 126
  • 127
  • 128
  • 129
  • 130
  • 131
  • 132
  • 133
  • 134
  • 135
  • 136
  • 137
  • 138
  • 139
  • 140
  • 141
  • 142
  • 143
  • 144
  • 145
  • 146
  • 147
  • 148
  • 149
  • 150
  • 151
  • 152
  • 153
  • 154

It's easy to use. Pass the correct url initialization and call the corresponding method. I don't want to roll and paste here. In addition, a third-party library AFSoundManager is recommended, which simplifies the iOS audio playback function, supports local files and streaming media, and is implemented through a fully Block-driven Objective-C class. Use Audio Toolbox and AV Foundation framework. I also encapsulated it in Demo. The usage is similar to that of the AdioPlayer we just encapsulated. Interested can see.  
demo:  
 
GitHub: https://github.com/FEverStar/AudioDemo

Copyright Statement: This article is the original article of the blogger. Please indicate the source for reprinting.

http://blog.csdn.net/liu1347508335/article/details/51097761

Posted by Patioman on Sat, 30 Mar 2019 14:12:30 -0700