iOS开发播放本地以及网络音乐

1、播放本地音乐
将音频文件添加到您的Xcode项目中。确保将音频文件的目标成员身份设置为您的应用程序。
导入AVFoundation框架,并在您的视图控制器或其他适当的位置添加以下代码:

#import <AVFoundation/AVFoundation.h>

在视图控制器的属性或适当的类扩展中声明AVAudioPlayer实例变量:
需要注意:
AVAudioPlayer不能作为局部变量!
AVAudioPlayer不能作为局部变量!
AVAudioPlayer不能作为局部变量!
否则会出现播放没声音的情况。

@property (nonatomic, strong) AVAudioPlayer *audioPlayer;

在需要播放音乐的地方,初始化并播放AVAudioPlayer实例。

NSString *audioFilePath = [[NSBundle mainBundle] pathForResource:@"music" ofType:@"mp3"];
NSURL *audioFileURL = [NSURL fileURLWithPath:audioFilePath];

NSError *error = nil;
self.audioPlayer = [[AVAudioPlayer alloc] initWithContentsOfURL:audioFileURL error:&error];
if (self.audioPlayer) {
    [self.audioPlayer play];
} else {
    NSLog(@"Failed to initialize audio player: %@", [error localizedDescription]);
}

请确保将"music"替换为您的音频文件的名称,并将"mp3"替换为您的音频文件的扩展名。
若要停止音乐播放,您可以调用stop方法:

[self.audioPlayer stop];

根据您的需求,您可能还需要处理音频的其他方面,例如处理播放进度、音量控制等。有关更多高级功能,请参考Apple的AVFoundation框架文档。

2、播放网络URL音乐
导入AVFoundation框架,并在您的视图控制器或其他适当的位置添加以下代码:

#import <AVFoundation/AVFoundation.h>

在视图控制器的属性或适当的类扩展中声明AVAudioPlayer实例变量:

@property (nonatomic, strong) AVAudioPlayer *audioPlayer;

在需要播放音乐的地方,初始化并播放AVAudioPlayer实例。

NSURL *audioURL = [NSURL URLWithString:@"https://example.com/music.mp3"];
AVPlayerItem *playerItem = [AVPlayerItem playerItemWithURL:audioURL];
self.player = [AVPlayer playerWithPlayerItem:playerItem];
[self.player play];

请将上述代码中的URL替换为您要播放的音乐的实际URL。

若要停止音乐播放,您可以调用pause方法:

[self.player pause];

播放网络URL音乐无限循环播放

#import <AVFoundation/AVFoundation.h>

@interface YourViewController ()
@property (nonatomic, strong) AVPlayer *player;
@property (nonatomic, strong) AVPlayerItem *playerItem;
@end

@implementation YourViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    // 设置音频URL
    NSURL *audioURL = [NSURL URLWithString:@"https://example.com/music.mp3"];
    self.playerItem = [AVPlayerItem playerItemWithURL:audioURL];
    
    // 监听播放完成通知
    [[NSNotificationCenter defaultCenter] addObserver:self
                                             selector:@selector(playerItemDidReachEnd:)
                                                 name:AVPlayerItemDidPlayToEndTimeNotification
                                               object:self.playerItem];
    
    // 初始化AVPlayer
    self.player = [AVPlayer playerWithPlayerItem:self.playerItem];
    
    // 开始播放音频
    [self.player play];
}

// 播放完成通知回调
- (void)playerItemDidReachEnd:(NSNotification *)notification {
    // 重置播放时间为0
    [self.playerItem seekToTime:kCMTimeZero];
    
    // 重新开始播放
    [self.player play];
}

- (void)dealloc {
    // 移除通知观察者
    [[NSNotificationCenter defaultCenter] removeObserver:self
                                                    name:AVPlayerItemDidPlayToEndTimeNotification
                                                  object:self.playerItem];
}

@end
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容