AVPlayer没声音

时间:2024-11-16 09:46:18

有可能是因为静音模式导致

  • 设置静音模式依然播放
AVAudioSession *audioSession = [AVAudioSession sharedInstance];
[audioSession setCategory:AVAudioSessionCategoryPlayback error:nil];
[audioSession setActive:YES error:nil];
AudioServicesCreateSystemSoundID
  • 对于比较短促的声音,比如系统的推送声音和短信声音,官方要求不要超过30s。
  • 优点:C语言的底层写法,节省内存。
  • 缺点:支持的格式有限,音量无法通过音量键控制,而且播放方式单一。
//开始播放
NSString *filePath = [[NSBundle mainBundle] pathForResource:@"done" ofType:@"wav"];
NSURL *fileUrl = [NSURL URLWithString:filePath];
SystemSoundID soundID = 0;
AudioServicesCreateSystemSoundID((__bridge CFURLRef)(fileUrl), &soundID);
AudioServicesAddSystemSoundCompletion(soundID,NULL,NULL,soundCompleteCallBack,NULL);
AudioServicesPlaySystemSound(soundID);
//播放完成
void soundCompleteCallBack(SystemSoundID soundID, void *clientData)
{
    NSLog(@"播放完成");
}

AVAudioPlayer
  • 适用于音乐时间比较长,或者对播放的控制性要求比较高的场景
  • 优点: 抒写效率更高,基本上支持所有的音频格式,对播放的控制,如循环播放,声音大小,暂停等比较方便。
  • 缺点: 相比上一种,对内存的消耗会多些。不支持流式,即无法播放在线音乐
if (!self.musicPlayer) {
        NSString *filePath = [[NSBundle mainBundle] pathForResource:@"happy_birthday" ofType:@"mp3"];
        NSURL *fileUrl = [NSURL URLWithString:filePath];
        self.musicPlayer = [[AVAudioPlayer alloc]initWithContentsOfURL:fileUrl error:nil];
        self.musicPlayer.delegate = self;
        //初始音量大小
		self.musicPlayer.volume = 1;
		//循环次数 0是一次  1是两次 2 是三次 以此类推  -1是一直循环
		self.musicPlayer..numberOfLoops = 0;
    }

if (![self.musicPlayer isPlaying]){
    [self.musicPlayer setVolume:0.6];
    [self.musicPlayer prepareToPlay];
    [self.musicPlayer play];
}
//暂停
if ([self.musicPlayer isPlaying]){
    [self.musicPlayer pause];
}
//播放完成
-(void)audioPlayerDidFinishPlaying:(AVAudioPlayer *)player successfully:(BOOL)flag
{
    [self.musicPlayer stop];
    self.musicPlayer=nil;
    self.musicPlayer.delegate = nil;
}


AVPlayer
  • 和AVAudioPlayer相似,但支持流播放,即可以播放在线的音乐
NSURL * url  = [NSURL URLWithString:@".mp3"];
NSURL * url2  = [[NSBundle mainBundle] URLForResource:@"mmusic" withExtension:@".mp3"];
AVPlayerItem * songItem = [[AVPlayerItem alloc]initWithURL:url]; 
self.player = [[AVPlayer alloc]initWithPlayerItem:songItem];
//AVPlayer * player = [[AVPlayer alloc] initWithURL:url];
//AVPlayerItem * songItem = ;
//1播放
[self.audioPlayer prepareToPlay];
[self.player play];
//2暂停
[self.player pause];
//3 切换上一首或者下一首
[self.player replaceCurrentItemWithPlayerItem:songItem];
 // 4.打印歌曲信息
@"音频文件声道数" =  self.audioPlayer.numberOfChannels;
@"音频文件持续时间" =  self.audioPlayer.duration;
// 4.设置循环播放
self.audioPlayer.volume = 1.0;
self.audioPlayer.numberOfLoops = -1;