首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >如何停止AudioToolbox声音?

如何停止AudioToolbox声音?
EN

Stack Overflow用户
提问于 2013-03-13 03:38:47
回答 1查看 1.2K关注 0票数 4

我有两个不同的按钮按下声音动作。当我按下一个按钮时,它应该播放一个声音,当我按下另一个按钮时,它应该停止第一个声音并播放另一个声音,我该怎么做呢?

谢谢,

代码语言:javascript
复制
-(void) onButtonPressAlbina {
    [soundID2 stop];     
    NSString *soundPath = [[NSBundle mainBundle] pathForResource:@"albina" ofType:@"m4a"];
    SystemSoundID soundID;
    AudioServicesCreateSystemSoundID((__bridge CFURLRef)[NSURL fileURLWithPath: soundPath], &soundID);
    AudioServicesPlaySystemSound (soundID);
}

-(void) onButtonPressBalena {
    NSString *soundPath = [[NSBundle mainBundle] pathForResource:@"balena" ofType:@"m4a"];
    SystemSoundID soundID;
    AudioServicesCreateSystemSoundID((__bridge CFURLRef)[NSURL fileURLWithPath: soundPath], &soundID);
    AudioServicesPlaySystemSound (soundID);    
}
EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2013-03-13 03:44:38

您不能停止通过"AudioServicesPlaySystemSound“播放的声音,但您可以使用"AVAudioPlayer”代替。

在你的对象中保留对"AVAudioPlayer“的引用,然后当你需要停止它的时候,你可以在它上面调用"stop"

代码语言:javascript
复制
#import <AudioToolbox/AudioToolbox.h>
#import <AVFoundation/AVAudioPlayer.h>
AVAudioPlayer  *player;

// ...

NSString *path;
NSError *error;
path = [[NSBundle mainBundle] pathForResource:@"albina" ofType:@"m4a"];
if ([[NSFileManager defaultManager] fileExistsAtPath:path]) 
{    
  player = [[AVAudioPlayer alloc] initWithContentsOfURL:[NSURL fileURLWithPath:path] error:&error];
  player.volume = 0.5f;
  [player prepareToPlay];
  [player setNumberOfLoops:0];
  [player play];    
} 

代码语言:javascript
复制
if (player != nil)
{
  if (player.isPlaying == YES)
    [player stop];
}
票数 3
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/15370584

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档