作者热门文章
- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
我有一个使用选择器 View 的具有多种声音的音乐播放器。我的问题是,当我单击下一首音乐时,上一首音乐将与我选择的音乐重叠。这意味着当我滚动选取器 View 以选择一个新对象时,它将播放新的音乐/声音,但上一个对象将重叠当前的选择。我想停止之前的音乐,这样就不会重叠。这是代码。
H 文件:
#import <UIKit/UIKit.h>
#import <AVFoundation/AVAudioPlayer.h>
@interface PickerViewController : UIViewController <UIPickerViewDelegate, UIPickerViewDataSource, AVAudioPlayerDelegate>{
UIPickerView *picker;
UILabel *musicTitle;
NSMutableArray *musicList;
AVAudioPlayer *audioPlayer;
}
@property (nonatomic, retain) IBOutlet UIPickerView *picker;
@property (nonatomic, retain) IBOutlet UILabel *musicTitle;
@property (nonatomic, retain) NSMutableArray *musicList;
-(IBAction)playSelectedMusic:(id)sender;
@end
M 文件:
- (void)viewDidLoad
{
[super viewDidLoad];
musicList = [[NSMutableArray alloc] initWithObjects:@"m1",@"m2",@"m3",@"m6",@"m4", @"m5",nil];
}
-(void)pickerView:(UIPickerView *)pickerView didSelectRow:(NSInteger)row inComponent:(NSInteger)component
{
if ([[musicList objectAtIndex:row] isEqual:@"m1"])
{
NSString *path = [[NSBundle mainBundle] pathForResource:@"m1" ofType:@"mp3"];
AVAudioPlayer* theAudio=[[AVAudioPlayer alloc] initWithContentsOfURL:[NSURL fileURLWithPath:path] error:NULL];
pickerView.delegate = self;
[theAudio play];
[theAudio setCurrentTime:0.0]; (our friend from this forum have suggested this but still doens't work)
NSString *resultString = [[NSString alloc] initWithFormat:
@"m1",
[musicList objectAtIndex:row]];
musicTitle.text = resultString;
}
if ([[musicList objectAtIndex:row] isEqual:@"m2"])
{
NSString *path = [[NSBundle mainBundle] pathForResource:@"m2" ofType:@"mp3"];
AVAudioPlayer* theAudio=[[AVAudioPlayer alloc] initWithContentsOfURL:[NSURL fileURLWithPath:path] error:NULL];
pickerView.delegate = self;
[theAudio play];
[theAudio setCurrentTime:0.0]; (our friend from this forum have suggested this but still doens't work)
NSString *resultString = [[NSString alloc] initWithFormat:
@"m2",
[musicList objectAtIndex:row]];
musicTitle.text = resultString;
}
代码修改:
NSString *path = [[NSBundle mainBundle] pathForResource:@"you" ofType:@"mp3"];
NSURL *file = [[NSURL alloc] initFileURLWithPath:path];
AVAudioPlayer* theAudio=[[AVAudioPlayer alloc] initWithContentsOfURL:file error:NULL];
[file release];
self.audioPlayer = theAudio;
[theAudio release];
[audioPlayer prepareToPlay];
[audioPlayer setDelegate:self];
[audioPlayer setNumberOfLoops:0];
[audioPlayer stop];
我的愚蠢错误:
@property (nonatomic, retain) AVAudioPlayer *audioPlayer;
最佳答案
只需停止当前正在播放的声音,然后再开始另一个声音,您的 AVAudioPlayer 是一个 ivar,因此您可以做到这一点。添加
[theAudio stop];
关于iphone - iOS : How to avoid overlapping sound/music in PickerViewController,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8726508/
我是一名优秀的程序员,十分优秀!