【音频播放】

聂建茗
2023-12-01

//限本地


//导入系统框架 AVFoundation.framework


#import <AVFoundation/AVFoundation.h>


    //把本地音频文件地址转成url

    NSURL *url = [NSURL fileURLWithPath:audioPath];


    //创建音乐播放器,并赋值资源的url

    _audioPlayer = [[AVAudioPlayer alloc] initWithContentsOfURL:url error:nil];

    //播放器会对播放资源进行预加载

    [_audioPlayer prepareToPlay];

    //播放

    [_audioPlayer play];


//音量

@property float volume;

//播放状态

@property(readonly, getter=isPlaying) BOOL playing;

//播放、暂停、停止

- (BOOL)play;

- (void)pause;

- (void)stop;


//播放进度

@property NSTimeInterval currentTime;

//总时长

@property(readonly) NSTimeInterval duration;


//代理方法之一:播放完成时的回调

- (void)audioPlayerDidFinishPlaying:(AVAudioPlayer *)player successfully:(BOOL)flag;



简单短小的音频播放:必须30秒以内,并且没有代理和其它的控制

//AudioToolbox.framework

    #import <AudioToolbox/AudioToolbox.h>

    SystemSoundID sound;

    AudioServicesCreateSystemSoundID((__bridge CFURLRef)(soundUrl), &sound);

    AudioServicesPlaySystemSound(sound);



【视频播放】

//可以播放本地和远程的

//导入系统框架 MediaPlayer.framework

#import <MediaPlayer/MediaPlayer.h>


NSString *videoPath = [[NSBundle mainBundle] pathForResource:@"1" ofType:@"mp4"];

  //本地视频

    NSURL *url = [NSURL fileURLWithPath:videoPath];

//远程视频

    url = [NSURL URLWithString:@"http://love.local/ShareDemo/1.mp4"];   


        //初始化带有视频播放器的控制器

        _playController  =[[MPMoviePlayerViewController alloc] initWithContentURL:url];

        //弹出视频播放器的界面

        [self presentViewController:_playController animated:YES completion:nil];



        //moviePlayer属性,为视频播放器,操作和音频类似,有准备,放,暂停等

        //指定播放的视频资源的类型,MPMovieSourceTypeFile(普通的文件类的视频资源)

       // _playController.moviePlayer.movieSourceType = MPMovieSourceTypeFile;


        //可以控制播放页面找到播放器

        //_playController.moviePlayer


        //监听播放完成事件(播放完成时会自动发送name:MPMoviePlayerPlaybackDidFinishNotification这个通知

        [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(playBack) name:MPMoviePlayerPlaybackDidFinishNotification object:nil];

    


- (void)playBack{

    //从通知中心,移除自身的观察者身份

    [[NSNotificationCenter defaultCenter] removeObserver:self name:MPMoviePlayerPlaybackDidFinishNotification object:nil];

    if (_playController) {

        //停止播放

        [_playController.moviePlayer stop];

        _playController = nil;

    }

}

 类似资料: